This package introduces a new error
type that combines an HTTP status code and a message. It helps with two things:
httperrors.HTTPError
and react depending on the status code or pass on the error as is.The httperrors.HTTPError
type implements the error
interface but also includes a WriteJSON(w http.ResponseWriter)
method that allows to convert the error into an HTTP response. It will set the HTTP status code and write the message as JSON to the response body like this:
{
"message": "missing field: username"
}
func myHandler(c framework.Context) error {
if c.FormValue("user") == "" {
return httperrors.New(http.StatusBadRequest, "missing field: username")
}
// ...
}
func generalErrorHandler(err error, c framework.Context) {
httpError, ok := err.(httperrors.HTTPError)
// Alternativly a type switch can be used to identify the HTTPError.
if ok {
httpError.WriteJSON(c.ResponseWriter)
return
}
// Handle other error types here ...
}
Version | Tag | Published |
---|---|---|
v1.0.0 | 1yr ago |