Documentation
¶
Overview ¶
Package httperrors provides an HTTP-aware error type modeled on the npm "http-errors" package, the module used internally by Express and Koa to build the errors that middleware turns into HTTP responses. Errors carry an HTTP status code, a message, and an "expose" flag indicating whether the message is safe to send to clients, so a single value can flow from the point of failure all the way to the response writer while carrying everything the handler needs to render it.
The Node http-errors package became the de facto standard because it lets application code fail with intent: instead of returning a bare error and separately deciding on a status code, a handler throws createError(404) or new NotFound() and the framework's error middleware reads the status straight off the error. This port brings that ergonomics to Go's error model. Error implements the standard error interface, so a *Error can be returned anywhere an error is expected, passed through errors.Is/As-style checks, and later recognized with IsHTTPError to recover its status and expose flag when writing the response.
Construct errors either generically with New(status, msg) or with one of the named constructors such as BadRequest, NotFound or InternalServerError, which simply call New with the corresponding net/http status constant. When the message is empty, New substitutes the standard status text for the code (via http.StatusText), so New(404, "") yields the message "Not Found". This matches http-errors, where omitting a message falls back to the canonical reason phrase, and it means the named constructors always produce a non-empty, human-readable message even when called with "".
The Expose field encodes the security convention at the heart of the original library: client errors are generally safe to describe to the caller, while server errors may contain internal detail that should not leak. Accordingly Expose defaults to true for 4xx status codes and false for 5xx status codes. Callers that want to override this (for example, to hide the message of a deliberately vague 403, or to surface a curated 503 message) can set the field directly on the returned *Error after construction, since it is a plain exported struct.
Parity with the Node package is close for the common path but not total. The constructors here cover the widely used 4xx and 5xx codes rather than every status http-errors defines, and this port models the status, message and expose semantics without http-errors' extra conveniences such as attaching arbitrary properties, header maps, or wrapping an existing error's stack. For status codes without a dedicated constructor, call New directly with the numeric code.
Index ¶
- func IsHTTPError(err error) bool
- type Error
- func BadGateway(msg string) *Error
- func BadRequest(msg string) *Error
- func Conflict(msg string) *Error
- func Forbidden(msg string) *Error
- func GatewayTimeout(msg string) *Error
- func Gone(msg string) *Error
- func InternalServerError(msg string) *Error
- func LengthRequired(msg string) *Error
- func MethodNotAllowed(msg string) *Error
- func New(status int, msg string) *Error
- func NotAcceptable(msg string) *Error
- func NotFound(msg string) *Error
- func NotImplemented(msg string) *Error
- func PayloadTooLarge(msg string) *Error
- func PreconditionFailed(msg string) *Error
- func RequestTimeout(msg string) *Error
- func ServiceUnavailable(msg string) *Error
- func TooManyRequests(msg string) *Error
- func Unauthorized(msg string) *Error
- func UnsupportedMediaType(msg string) *Error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsHTTPError ¶
IsHTTPError reports whether err is (or wraps) an *Error from this package.
Example ¶
ExampleIsHTTPError shows how to recognize errors produced by this package. IsHTTPError reports whether a value returned as a plain error is actually an *Error, which lets response-writing code recover the status and expose flag. A value created by New or any named constructor reports true, while an ordinary error created elsewhere reports false. This is the typical bridge between application code that returns errors and middleware that must decide on a status code. Here a NotFound is recognized while a plain error is not.
package main
import (
"errors"
"fmt"
"github.com/malcolmston/express/httperrors"
)
func main() {
fmt.Println(httperrors.IsHTTPError(httperrors.NotFound("")))
fmt.Println(httperrors.IsHTTPError(errors.New("plain")))
}
Output: true false
Types ¶
type Error ¶
type Error struct {
// Status is the HTTP status code associated with the error.
Status int
// Message is the human-readable error text returned by Error.
Message string
// Expose reports whether Message is safe to send to clients. It defaults
// to true for 4xx status codes and false for 5xx status codes.
Expose bool
}
Error is an error carrying an HTTP status code.
Status is the HTTP status code. Message is the human readable error message returned by Error. Expose reports whether the message is safe to expose to clients; by convention it defaults to true for 4xx client errors and false for 5xx server errors.
func BadRequest ¶
BadRequest returns a 400 Bad Request error.
Example ¶
ExampleBadRequest illustrates supplying a custom message to a named constructor. When a non-empty message is given it is used verbatim instead of the default status text, so the error reads exactly as written. The status is still fixed by the constructor, here 400. Custom messages are handy for validation failures where the specific problem should be reported. Because this is a 4xx error, the message remains exposable to the client by default.
package main
import (
"fmt"
"github.com/malcolmston/express/httperrors"
)
func main() {
e := httperrors.BadRequest("email is required")
fmt.Println(e.Status)
fmt.Println(e.Error())
}
Output: 400 email is required
func GatewayTimeout ¶
GatewayTimeout returns a 504 Gateway Timeout error.
func InternalServerError ¶
InternalServerError returns a 500 Internal Server Error error.
Example ¶
ExampleInternalServerError demonstrates the 5xx behavior around the Expose flag. Server errors may contain internal detail, so their message is not marked safe to send to clients: Expose defaults to false for any 5xx code. The default message still comes from the standard status text when none is supplied. This lets a handler signal a 500 without accidentally leaking implementation details to the caller. Applications that want to surface a curated message can set the Expose field on the returned error directly.
package main
import (
"fmt"
"github.com/malcolmston/express/httperrors"
)
func main() {
e := httperrors.InternalServerError("")
fmt.Println(e.Status)
fmt.Println(e.Message)
fmt.Println(e.Expose)
}
Output: 500 Internal Server Error false
func LengthRequired ¶
LengthRequired returns a 411 Length Required error.
func MethodNotAllowed ¶
MethodNotAllowed returns a 405 Method Not Allowed error.
func New ¶
New creates a new *Error with the given status code and message.
If msg is empty the standard status text for the code is used. Expose defaults to true for 4xx status codes and false for 5xx status codes.
Example ¶
ExampleNew builds an error from a status code and message. When the message is empty, New substitutes the standard reason phrase for the code, so New(404, "") produces the message "Not Found". The Expose flag is derived from the status class: 4xx codes default to exposable because client errors are generally safe to describe. The returned *Error satisfies the error interface, and its Error method returns the message. This makes New a one-line way to create a fully populated HTTP error.
package main
import (
"fmt"
"github.com/malcolmston/express/httperrors"
)
func main() {
e := httperrors.New(404, "")
fmt.Println(e.Status)
fmt.Println(e.Error())
fmt.Println(e.Expose)
}
Output: 404 Not Found true
func NotAcceptable ¶
NotAcceptable returns a 406 Not Acceptable error.
func NotFound ¶
NotFound returns a 404 Not Found error.
Example ¶
ExampleNotFound shows one of the named constructors, which are thin wrappers around New using the matching net/http status constant. Passing an empty message falls back to the canonical status text, here "Not Found". Like all 4xx helpers, NotFound marks the error as exposable. These constructors read clearly at the call site, letting handlers fail with intent such as returning httperrors.NotFound(""). The resulting value carries the 404 status for middleware to translate into a response.
package main
import (
"fmt"
"github.com/malcolmston/express/httperrors"
)
func main() {
e := httperrors.NotFound("")
fmt.Println(e.Status)
fmt.Println(e.Message)
fmt.Println(e.Expose)
}
Output: 404 Not Found true
func NotImplemented ¶
NotImplemented returns a 501 Not Implemented error.
func PayloadTooLarge ¶
PayloadTooLarge returns a 413 Payload Too Large error.
func PreconditionFailed ¶
PreconditionFailed returns a 412 Precondition Failed error.
func RequestTimeout ¶
RequestTimeout returns a 408 Request Timeout error.
func ServiceUnavailable ¶
ServiceUnavailable returns a 503 Service Unavailable error.
func TooManyRequests ¶
TooManyRequests returns a 429 Too Many Requests error.
func Unauthorized ¶
Unauthorized returns a 401 Unauthorized error.
func UnsupportedMediaType ¶
UnsupportedMediaType returns a 415 Unsupported Media Type error.