errors: github.com/spacemonkeygo/errors/errhttp Index | Examples | Files

package errhttp

import "github.com/spacemonkeygo/errors/errhttp"

Package errhttp provides some useful helpers on top of the errors package for HTTP handling.

errhttp is a great example of how to use the errors package SetData and GetData hierarchical methods.

Code:

package main

import (
    "log"
    "net/http"
    "testing"

    "github.com/spacemonkeygo/errors"
)

func writeError(msg string, code int) {}

func main(t *testing.T) {
    InvalidRequest := errors.NewClass("Invalid request",
        SetStatusCode(http.StatusBadRequest))

    process := func() error {
        // this method is some sample method somewhere that's doing request
        // processing
        return InvalidRequest.New("missing field or something")
    }

    handler := func(err error) {
        // this method is some sample method somewhere that's figuring out how
        // to display various errors to a user.
        if err != nil {
            code := GetStatusCode(err, 500)
            message := GetErrorBody(err)
            log.Printf("HTTP error %d: %s\n%s", code, message, err)
            writeError(message, code)
        }
    }

    // http event loop
    handler(process())
}

Index

Examples

Package Files

http.go

func GetErrorBody Uses

func GetErrorBody(err error) string

GetErrorBody will return the user-visible error message given an error. The message will be determined by errors.GetMessage() unless the error class has an error body overridden by OverrideErrorBody.

func GetStatusCode Uses

func GetStatusCode(err error, default_code int) int

GetStatusCode will return the status code associated with an error, and default_code if none is found.

func OverrideErrorBody Uses

func OverrideErrorBody(message string) errors.ErrorOption

OverrideErrorBody returns an ErrorOption (for use in ErrorClass creation or error instantiation) that controls the error body seen by GetErrorBody.

func RestoreDefaultErrorBody Uses

func RestoreDefaultErrorBody() errors.ErrorOption

RestoreDefaultErrorBody returns an ErrorOption (for use in ErrorClass creation or error instantiation) that restores the default error body shown by GetErrorBody for some subhierarchy of errors.

func SetStatusCode Uses

func SetStatusCode(code int) errors.ErrorOption

SetStatusCode returns an ErrorOption (for use in ErrorClass creation or error instantiation) that controls the error's HTTP status code

Package errhttp imports 2 packages (graph) and is imported by 8 packages. Updated 2016-07-19. Refresh now. Tools for package owners.