33 lines
1.0 KiB
Go
33 lines
1.0 KiB
Go
|
|
package commonservice
|
|||
|
|
|
|||
|
|
// AppError 是带稳定错误码与 HTTP 状态的业务错误,控制器原样返回 {"error":"CODE"}。
|
|||
|
|
type AppError struct {
|
|||
|
|
Code string
|
|||
|
|
Status int
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (e *AppError) Error() string {
|
|||
|
|
if e == nil {
|
|||
|
|
return ""
|
|||
|
|
}
|
|||
|
|
return e.Code
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// AsAppError 从 error 中取出 AppError;非业务错误返回 false。
|
|||
|
|
func AsAppError(err error) (*AppError, bool) {
|
|||
|
|
if err == nil {
|
|||
|
|
return nil, false
|
|||
|
|
}
|
|||
|
|
if ae, ok := err.(*AppError); ok {
|
|||
|
|
return ae, true
|
|||
|
|
}
|
|||
|
|
return nil, false
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func BadRequest(code string) *AppError { return &AppError{Code: code, Status: 400} }
|
|||
|
|
func Unauthorized(code string) *AppError { return &AppError{Code: code, Status: 401} }
|
|||
|
|
func Forbidden(code string) *AppError { return &AppError{Code: code, Status: 403} }
|
|||
|
|
func NotFound(code string) *AppError { return &AppError{Code: code, Status: 404} }
|
|||
|
|
func Conflict(code string) *AppError { return &AppError{Code: code, Status: 409} }
|
|||
|
|
func Internal(code string) *AppError { return &AppError{Code: code, Status: 500} }
|