// errmsg.go
package main
import (
"errors"
"fmt"
)
type DivideError struct {
dividee int
divider int
}
func (de *DivideError) Error() string {
strFormat := `
Cannot proceed, the divider is zero.
dividee: %d
divider: %d
`
return fmt.Sprintf(strFormat, de.dividee, de.divider)
}
func PrintErrTest() error {
return errors.New("error!!!!")
}
func Divide(varDividee int, varDivider int) (result int, errormsg string) {
if varDivider == 0 {
dData := DivideError{
dividee: varDividee,
divider: varDivider,
}
errormsg = dData.Error()
return
} else {
return varDividee / varDivider, ""
}
}
func main() {
// 1
error := PrintErrTest()
if error != nil {
fmt.Println(error)
}
// 2
if result, errorMsg := Divide(100, 10); errorMsg == "" {
fmt.Println("100/10 =", result)
}
if _, errorMsg := Divide(100, 0); errorMsg != "" {
fmt.Println("errorMsg is :", errorMsg)
}
}
输出:
error!!!!
100/10 = 10
errorMsg is :
Cannot proceed, the divider is zero.
dividee: 100
divider: 0