responsable-errors/interface.go

67 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-01-16 21:53:03 -06:00
package errors
2024-01-21 13:50:13 -06:00
import "encoding/json"
2024-01-16 21:53:03 -06:00
// 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.
//
// Status should return an appropriate HTTP status. It must not return < 100 || >= 600.
//
// Msg should return a message suitable to display to the end user. If the message
2024-01-16 21:53:03 -06:00
// returned by Error is safe for the end user, it may simply call that.
2024-01-21 13:50:13 -06:00
//
// 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()
2024-01-16 21:53:03 -06:00
type ResponsableError interface {
2024-01-21 13:50:13 -06:00
json.Marshaler
2024-01-16 21:53:03 -06:00
Error() string
Status() int
Msg() string
2024-01-21 13:50:13 -06:00
JSON() any
2024-01-16 21:53:03 -06:00
}
2024-01-17 15:51:28 -06:00
// SettableError is a ResponsableError which can be modified after initial creation.
//
// The SetStatus method can set the status, while the SetMsg method can set user message.
2024-01-17 15:51:28 -06:00
// If any values are passed after the message, it should be passed to fmt.Sprintf for formatting.
//
2024-01-17 15:51:28 -06:00
// Methods are chainable.
//
2024-01-17 15:51:28 -06:00
// SetStatus should not use a value outside of 100-599. It may either ignore such values, or panic.
2024-01-21 13:50:13 -06:00
//
// SetField should add some metadata to the error, which will be included in the data returned by JSON()
2024-01-17 15:51:28 -06:00
type SettableError interface {
ResponsableError
SetStatus(int) SettableError
SetMsg(string, ...any) SettableError
2024-01-21 13:50:13 -06:00
SetField(string, any) SettableError
2024-01-17 15:51:28 -06:00
}
2024-01-16 21:53:03 -06:00
// UnwrappableError allows a ResponsableError to wrap another error.
// It may be appropriate for Error() to delegate to the wrapped error.
type UnwrappableError interface {
ResponsableError
Unwrap() error
}
// UnwrappableErrorrs allows a ResponsableError to wrap multiple errors.
// It may be appropriate for Error() to either delegate to the first error,
// the last error, or to concatenate the return values of all wrapped errors,
// similar to errors returned by errors.Join
type UnwrappableErrors interface {
ResponsableError
Unwrap() []error
}
2024-01-17 10:58:39 -06:00
type wrappedError interface {
Error() string
Unwrap() error
}
type wrappedErrors interface {
Error() string
Unwrap() []error
}