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,5 +1,7 @@
package errors
import "encoding/json"
// ResponsableError is an error that has information useful in an HTTP response.
// The string returned by Error should be suitable for logging useful information
// to assist debugging the error.
@ -8,10 +10,16 @@ package errors
//
// Msg should return a message suitable to display to the end user. If the message
// returned by Error is safe for the end user, it may simply call that.
//
// JSON should return something that can be marshalled to JSON for the response body.
// It can be something as simple as map[string]string{"error":err.Msg()}.
// JSON's return value should be used by MarshalJSON()
type ResponsableError interface {
json.Marshaler
Error() string
Status() int
Msg() string
JSON() any
}
// SettableError is a ResponsableError which can be modified after initial creation.
@ -22,10 +30,13 @@ type ResponsableError interface {
// Methods are chainable.
//
// SetStatus should not use a value outside of 100-599. It may either ignore such values, or panic.
//
// SetField should add some metadata to the error, which will be included in the data returned by JSON()
type SettableError interface {
ResponsableError
SetStatus(int) SettableError
SetMsg(string, ...any) SettableError
SetField(string, any) SettableError
}
// UnwrappableError allows a ResponsableError to wrap another error.