Categorygithub.com/peeveen/httperrorhandler
modulepackage
0.2.3
Repository: https://github.com/peeveen/httperrorhandler.git
Documentation: pkg.go.dev

# README

httperrorhandler

Error handling hook & helper function to simplify writing API handler methods in Go.

Tries to follow the RFC-7807 recommendation for HTTP errors.

Example usage

import (
	httperr "github.com/peeveen/httperrorhandler"
)

...

func (s *server) handleSomeAPIRequest() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		httperr.Handle(w, r, func(w http.ResponseWriter, r *http.Request) *httperr.Error {
			// Do stuff
			if somethingHasGoneTerriblyWrong {
				return &httperr.Error{Type: "http://myapp/valve/blockage", Status: http.StatusInternalServerError, Detail: "There has been a defluter valve blockage."}
			}
			err := thirdPartyDoodah.doSomething()
			if err != nil {
				return httperr.Wrap(err, &httperr.Error{Type: "http://myapp/internal", Status: http.StatusInternalServerError, Detail: "The doodah has failed!"})
			}
		}, httperr.DefaultErrorHandler)
	}
}

Error handling

There is a default error handler implementation available (httperrorhandler.DefaultErrorHandler), or you can provide your own.

The default implementation will write the HTTP status code and the JSON representation of the error to the response as the application/problem+json content type.

# Functions

DefaultErrorHandler is a default handler for HTTP errors that you can use if you choose.
Handle makes a call to the given hander function, and, in the event of an HTTP server error result, calls your supplied error handler function.
Wrap returns an HTTP error object that wraps the given error.

# Structs

Error describes an error that occurred during the handling of an HTTP request.

# Type aliases

Handler is a function that handles an HTTP error, probably by writing the error details to the response.