forked from mtusi2026/mtusi2026lab2
124 lines
1.7 KiB
Go
124 lines
1.7 KiB
Go
package apperr
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
grpcCodes "google.golang.org/grpc/codes"
|
|
)
|
|
|
|
type AppError struct {
|
|
err error
|
|
msg string
|
|
code Code
|
|
meta metadata
|
|
}
|
|
|
|
func New(code Code, msg string) error {
|
|
return &AppError{
|
|
msg: msg,
|
|
code: code,
|
|
meta: metadata{},
|
|
}
|
|
}
|
|
|
|
func Wrap(err error, code Code, msg string) error {
|
|
m := AppError{
|
|
err: err,
|
|
msg: msg,
|
|
code: code,
|
|
meta: metadata{},
|
|
}
|
|
return &m
|
|
}
|
|
|
|
func WrapAppError(err error, msg string) error {
|
|
m := AppError{
|
|
err: err,
|
|
msg: msg,
|
|
code: CodeInternal,
|
|
meta: metadata{},
|
|
}
|
|
|
|
if mistake := As(err); mistake != nil {
|
|
m.err = mistake
|
|
m.code = mistake.code
|
|
m.meta = mistake.meta
|
|
}
|
|
|
|
return &m
|
|
}
|
|
|
|
func As(err error) *AppError {
|
|
if mistakeErr, ok := errors.AsType[*AppError](err); ok {
|
|
return mistakeErr
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func CodeIs(err error, code Code) bool {
|
|
if appErr := As(err); appErr != nil && appErr.Code() == code {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (e *AppError) Error() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
|
|
if e.err == nil {
|
|
if e.msg != "" {
|
|
return e.msg
|
|
}
|
|
return e.code.String()
|
|
}
|
|
|
|
if e.msg == "" {
|
|
return e.err.Error()
|
|
}
|
|
|
|
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
|
|
}
|
|
|
|
func (e *AppError) Unwrap() error {
|
|
if e == nil {
|
|
return nil
|
|
}
|
|
return e.err
|
|
}
|
|
|
|
func (e *AppError) Code() Code {
|
|
if e == nil {
|
|
return CodeInternal
|
|
}
|
|
return e.code
|
|
}
|
|
|
|
func (e *AppError) Message() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
return e.msg
|
|
}
|
|
|
|
func (e *AppError) Cause() error {
|
|
if e == nil {
|
|
return nil
|
|
}
|
|
return e.err
|
|
}
|
|
|
|
func (e *AppError) Metadata() Metadata {
|
|
return e.meta
|
|
}
|
|
|
|
func (e *AppError) HTTPStatus() int {
|
|
return e.Code().HTTPStatus()
|
|
}
|
|
|
|
func (e *AppError) GRPCCode() grpcCodes.Code {
|
|
return e.Code().GRPCCode()
|
|
}
|