创建自定义错误类型
在 Go 中,错误由可以将自身描述为字符串的任何值表示。任何实现内置 error
接口的类型都是错误的。
// The error interface is represented by a single
// Error() method, that returns a string representation of the error
type error interface {
Error() string
}
以下示例显示如何使用字符串复合文字定义新的错误类型。
// Define AuthorizationError as composite literal
type AuthorizationError string
// Implement the error interface
// In this case, I simply return the underlying string
func (e AuthorizationError) Error() string {
return string(e)
}
我现在可以使用我的自定义错误类型作为错误:
package main
import (
"fmt"
)
// Define AuthorizationError as composite literal
type AuthorizationError string
// Implement the error interface
// In this case, I simply return the underlying string
func (e AuthorizationError) Error() string {
return string(e)
}
func main() {
fmt.Println(DoSomething(1)) // succeeds! returns nil
fmt.Println(DoSomething(2)) // returns an error message
}
func DoSomething(someID int) error {
if someID != 1 {
return AuthorizationError("Action not allowed!")
}
// do something here
// return a nil error if the execution succeeded
return nil
}