wherr

package
v1.0.0-...-3f30213 Latest Latest
Warning

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

Go to latest
Published: May 30, 2017 License: Apache-2.0 Imports: 8 Imported by: 20

Documentation

Overview

Package wherr provides a unified error handling framework for http.Handlers.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/spacemonkeygo/errors/errhttp"
	"gopkg.in/webhelp.v1/wherr"
	"gopkg.in/webhelp.v1/whlog"
	"gopkg.in/webhelp.v1/whmux"
)

func PageName(r *http.Request) (string, error) {
	if r.FormValue("name") == "" {
		return "", wherr.BadRequest.New("No page name supplied")
	}
	return r.FormValue("name"), nil
}

func Page(w http.ResponseWriter, r *http.Request) {
	name, err := PageName(r)
	if err != nil {
		// This will use our error handler!
		wherr.Handle(w, r, err)
		return
	}

	fmt.Fprintf(w, name)
	// do more stuff
}

func Routes() http.Handler {
	return whmux.Dir{
		"page": http.HandlerFunc(Page),
	}
}

func ErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
	http.Error(w, "some error happened!", errhttp.GetStatusCode(err, 500))
}

func main() {
	// If we didn't register our error handler, we'd end up using a default one.
	whlog.ListenAndServe(":0", wherr.HandleWith(wherr.HandlerFunc(ErrorHandler),
		Routes()))
}
Output:

Index

Examples

Constants

This section is empty.

Variables

Functions

func ErrorClass

func ErrorClass(code int) *errors.ErrorClass

ErrorClass creates a new subclass of HTTPError using the given HTTP status code

func Handle

func Handle(w http.ResponseWriter, r *http.Request, err error)

Handle uses the provided error handler given via HandleWith to handle the error, falling back to a built in default if not provided.

func HandleWith

func HandleWith(eh Handler, h http.Handler) http.Handler

HandleWith binds the given eror Handler to the request contexts that pass through the given http.Handler. wherr.Handle will use this error Handler for handling errors. If you're using the whfatal package, you should place a whfatal.Catch inside this handler, so this error handler can deal with Fatal requests.

Types

type Handler

type Handler interface {
	HandleError(w http.ResponseWriter, r *http.Request, err error)
}

Handlers handle errors. After HandleError returns, it's assumed a response has been written out and all error handling has completed.

func HandlingWith

func HandlingWith(ctx context.Context) Handler

HandlingWith returns the error handler if registered, or nil if no error handler is registered and the default should be used.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request, err error)

func (HandlerFunc) HandleError

func (f HandlerFunc) HandleError(w http.ResponseWriter, r *http.Request,
	err error)

Jump to

Keyboard shortcuts

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