Files
nl-pms-api/internal/commonservice/errors.go
2026-08-15 17:04:47 +08:00

33 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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} }