Last active
December 16, 2020 10:02
-
-
Save kentokento/deaaeec71cf3f51fb963d4851ae3db1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package errors | |
import ( | |
"fmt" | |
"golang.org/x/xerrors" | |
) | |
// エラー構造体 | |
type appError struct { | |
// 標準のエラー仕様を満たす変数 | |
next error | |
message string | |
frame xerrors.Frame | |
// 独自の拡張仕様の変数 | |
data []map[string]interface{} | |
level level | |
// APIエラー | |
code string | |
infoMessage string | |
status int | |
} | |
func (e *appError) Error() string { | |
// 一番下位層のメッセージを取り出す | |
next := AsAppError(e.next) | |
if next != nil { | |
return next.Error() | |
} | |
if e.next == nil { | |
if e.message != `` { | |
return e.message | |
} | |
return `no message` | |
} | |
return e.next.Error() | |
} | |
func (e *appError) Is(err error) bool { | |
if er := AsAppError(err); er != nil { | |
return e.Code() == er.Code() | |
} | |
return false | |
} | |
func (e *appError) Unwrap() error { return e.next } | |
func (e *appError) Format(s fmt.State, v rune) { xerrors.FormatError(e, s, v) } | |
func (e *appError) FormatError(p xerrors.Printer) error { | |
var message string | |
if e.level != "" { | |
message += fmt.Sprintf("[%s] ", e.level) | |
} | |
if e.code != "" { | |
message += fmt.Sprintf("[%s] ", e.code) | |
} | |
if e.message != "" { | |
message += fmt.Sprintf("%s", e.message) | |
} | |
if len(e.data) != 0 { | |
if message != "" { | |
message += "\n" | |
} | |
message += fmt.Sprintf("data: %+v", e.data) | |
} | |
p.Print(message) | |
e.frame.Format(p) | |
return e.next | |
} | |
func (e *appError) AddData(field string, data interface{}) AppError { | |
if e.data == nil { | |
e.data = make([]map[string]interface{}, 0) | |
} | |
e.data = append(e.data, map[string]interface{}{field: data}) | |
return e | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment