✨ Add JSON marshalling
This commit is contained in:
parent
f27c669aeb
commit
2895433239
3 changed files with 54 additions and 2 deletions
23
errorf.go
23
errorf.go
|
|
@ -1,6 +1,7 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
|
@ -16,13 +17,14 @@ import (
|
|||
//
|
||||
// err := errors.Errorf(http.StatusNotFound, "%w", sqlError).SetMsg("user not found %d", userId)
|
||||
func Errorf(status int, format string, parts ...any) SettableError {
|
||||
meta := make(map[string]any)
|
||||
if len(parts) == 0 {
|
||||
return &erf{status, format, ""}
|
||||
return &erf{status, format, "", meta}
|
||||
}
|
||||
|
||||
err := fmt.Errorf(format, parts...)
|
||||
msg := err.Error()
|
||||
er := &erf{status, msg, ""}
|
||||
er := &erf{status, msg, "", meta}
|
||||
if we, ok := err.(wrappedError); ok {
|
||||
return &wrapErr{er, we.Unwrap()}
|
||||
}
|
||||
|
|
@ -34,11 +36,13 @@ func Errorf(status int, format string, parts ...any) SettableError {
|
|||
|
||||
var _ ResponsableError = new(erf)
|
||||
var _ SettableError = new(erf)
|
||||
var _ json.Marshaler = new(erf)
|
||||
|
||||
type erf struct {
|
||||
stat int
|
||||
err string
|
||||
msg string
|
||||
meta map[string]any
|
||||
}
|
||||
|
||||
func (e *erf) Status() int {
|
||||
|
|
@ -76,6 +80,21 @@ func (e *erf) SetMsg(msg string, parts ...any) SettableError {
|
|||
return e
|
||||
}
|
||||
|
||||
func (e *erf) SetField(field string, value any) SettableError {
|
||||
e.meta[field] = value
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *erf) JSON() any {
|
||||
m := e.meta
|
||||
m["error"] = e.Msg()
|
||||
return m
|
||||
}
|
||||
|
||||
func (e *erf) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(e.JSON())
|
||||
}
|
||||
|
||||
var _ UnwrappableError = new(wrapErr)
|
||||
|
||||
type wrapErr struct {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue