From 58f8497997df5043791f0d6338ed4be321777823 Mon Sep 17 00:00:00 2001 From: Gaze Date: Tue, 26 Nov 2024 14:39:27 +0700 Subject: [PATCH] feat: add code to errs.PublicError --- common/errs/public_errs.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/common/errs/public_errs.go b/common/errs/public_errs.go index 8eac68e8..0f74a13c 100644 --- a/common/errs/public_errs.go +++ b/common/errs/public_errs.go @@ -11,6 +11,7 @@ import ( type PublicError struct { err error message string + code string // code is optional, it can be used to identify the error type } func (p PublicError) Error() string { @@ -21,6 +22,10 @@ func (p PublicError) Message() string { return p.message } +func (p PublicError) Code() string { + return p.code +} + func (p PublicError) Unwrap() error { return p.err } @@ -29,6 +34,10 @@ func NewPublicError(message string) error { return withstack.WithStackDepth(&PublicError{err: errors.New(message), message: message}, 1) } +func NewPublicErrorWithCode(message string, code string) error { + return withstack.WithStackDepth(&PublicError{err: errors.New(message), message: message, code: code}, 1) +} + func WithPublicMessage(err error, prefix string) error { if err == nil { return nil @@ -41,3 +50,16 @@ func WithPublicMessage(err error, prefix string) error { } return withstack.WithStackDepth(&PublicError{err: err, message: message}, 1) } + +func WithPublicMessageCode(err error, prefix string, code string) error { + if err == nil { + return nil + } + var message string + if prefix != "" { + message = fmt.Sprintf("%s: %s", prefix, err.Error()) + } else { + message = err.Error() + } + return withstack.WithStackDepth(&PublicError{err: err, message: message, code: code}, 1) +}