Add JSON marshalling

This commit is contained in:
Dan Jones 2024-01-21 13:50:13 -06:00
commit 2895433239
3 changed files with 54 additions and 2 deletions

View file

@ -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 {