httperr

package
v0.0.0-...-544aadc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 10, 2024 License: MIT Imports: 8 Imported by: 10

Documentation

Index

Examples

Constants

View Source
const (
	Handled    = true
	NotHandled = false
)

Variables

View Source
var (
	DebugShowInternalErrorsInResponse       bool
	DebugShowInternalErrorsInResponseFormat = "\n%+v"

	DefaultHandler Handler = HandlerFunc(DefaultHandlerImpl)

	// SentinelHandlers is used by DefaultHandlerImpl to map
	// wrapped sentinel errors to corresponding http.Handler.
	// By default os.ErrNotExist and sql.ErrNoRows are mapped
	// to handlers that write a "404 Not Found" response.
	SentinelHandlers = map[error]http.Handler{
		os.ErrNotExist: http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
			http.Error(writer, "Requested file not found", http.StatusNotFound)
		}),
		sql.ErrNoRows: http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
			http.Error(writer, "Requested database row not found", http.StatusNotFound)
		}),
	}
)
View Source
var (
	BadRequest       = New(http.StatusBadRequest)       // 400: RFC 7231, 6.5.1
	Unauthorized     = New(http.StatusUnauthorized)     // 401: RFC 7235, 3.1
	PaymentRequired  = New(http.StatusPaymentRequired)  // 402: RFC 7231, 6.5.2
	Forbidden        = New(http.StatusForbidden)        // 403: RFC 7231, 6.5.3
	NotFound         = New(http.StatusNotFound)         // 404: RFC 7231, 6.5.4
	MethodNotAllowed = New(http.StatusMethodNotAllowed) // 405: RFC 7231, 6.5.5
)

Functions

func AsError

func AsError(val any) error

AsError converts val to an error by either casting val to error if possible, or using its string value or String method as error message, or using fmt.Errorf("%+v", val) to format the value as error.

func DefaultHandlerImpl

func DefaultHandlerImpl(err error, writer http.ResponseWriter, request *http.Request) (responseWritten bool)

DefaultHandlerImpl checks if err unwraps to a http.Handler and calls its ServeHTTP method else it checks if err wrapped any key in SentinelHandlers and calls ServeHTTP of the http.Handler value. In all other cases a 500 Internal Server Error response is written. If DebugShowInternalErrorsInResponse is true, then err.Error() message is added to the response. If err is nil, then no response is written and the function returns false. If an error response was written, then the function returns true.

func DontLog

func DontLog(err error) error

DontLog wraps the passed error so that ShouldLog returns false. A nil error won't be wrapped but returned as nil.

httperr.ShouldLog(httperr.BadRequest) == true
httperr.ShouldLog(httperr.DontLog(httperr.BadRequest)) == false
Example
fmt.Println(ShouldLog(BadRequest))
fmt.Println(ShouldLog(DontLog(BadRequest)))
Output:

true
false

func ForEachHandler

func ForEachHandler(err error, writer http.ResponseWriter, request *http.Request, handlers ...Handler) (handledAny bool)

func Handle

func Handle(err error, writer http.ResponseWriter, request *http.Request) (handled bool)

Handle will call DefaultHandler.HandleError(err, writer, request)

func HandlePanic

func HandlePanic(recoverResult any, writer http.ResponseWriter, request *http.Request) (handled bool)

HandlePanic will call DefaultHandler.HandleError(AsError(recoverResult), writer, request)

func ShouldLog

func ShouldLog(err error) bool

ShouldLog checks if the passed error has been wrapped with DontLog. A nil error results in false.

httperr.ShouldLog(httperr.BadRequest) == true
httperr.ShouldLog(httperr.DontLog(httperr.BadRequest)) == false

func WriteAsJSON

func WriteAsJSON(err any, statusCode int, writer http.ResponseWriter)

WriteAsJSON unmarshals err as JSON and writes it as application/json response body using the passed statusCode. If err could not be marshalled as JSON, then an internal server error will be written instead using WriteInternalServerError with a wrapped erorr message.

func WriteHandler

func WriteHandler(err error, writer http.ResponseWriter, request *http.Request) (responseWritten bool)

WriteHandler checks if err unwraps to a http.Handler and calls its ServeHTTP method else it checks if err wrapped any key in SentinelHandlers and calls ServeHTTP of the http.Handler value. If an error response was written, then the function returns true.

func WriteInternalServerError

func WriteInternalServerError(err any, writer http.ResponseWriter)

WriteInternalServerError writes err as 500 Internal Server Error reponse. If Logger is not nil, then it will be used to log an error message. If DebugShowInternalErrorsInResponse is true, then the error message will be shown in the response body, else only "Internal Server Error" will be used.

Types

type Handler

type Handler interface {
	HandleError(err error, writer http.ResponseWriter, request *http.Request) (handled bool)
}

type HandlerFunc

type HandlerFunc func(err error, writer http.ResponseWriter, request *http.Request) (handled bool)

func (HandlerFunc) HandleError

func (f HandlerFunc) HandleError(err error, writer http.ResponseWriter, request *http.Request) (handled bool)

type Response

type Response interface {
	error
	http.Handler
}

Response extends the error interface with the http.Handler interface to enable errors which can render themselves as HTTP responses.

func Errorf

func Errorf(statusCode int, format string, a ...any) Response

func JSON

func JSON(statusCode int, body any) Response

JSON returns a Response error that will respond with the passed statusCode, the content type application/json and the passed body marshalled as JSON. Pass a json.RawMessage as body if the error message is already in JSON format.

func New

func New(statusCode int, statusText ...string) Response

func NewFromResponse

func NewFromResponse(resonse *http.Response) Response

func PermanentRedirect

func PermanentRedirect(targetURL string) Response

func Redirect

func Redirect(statusCode int, targetURL string) Response

func TemporaryRedirect

func TemporaryRedirect(targetURL string) Response

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL