Skip to content

srfrog/fail

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fail GoDoc ghit.me Go Report Card

Manage and handle Go errors with nice and correct HTTP responses.

Fail allows to wrap errors and describe them as HTTP responses, such as, "Not Found" and "Bad Request" and their status code. Also, help you mask internal errors with friendly messages that are appropriate for clients.

The goal of this package is to handle the behavior of errors to minimize static errors and type assertions. If all errors are wrapped with fail.Cause we can inspect them better and give clients proper responses.

This package is inspired by Dave Cheney's excellent blog post "Don’t just check errors, handle them gracefully".

Quick Start

Install using "go get":

go get github.com/codehack/fail

Then import from your source:

import "github.com/codehack/fail"

Documentation

The documentation at GoDoc:

http://godoc.org/github.com/codehack/fail

Example

package main

import "github.com/codehack/fail"

// Create a new user, using JSON values.
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
	// we want a POST request, this will fail.
	if r.Method != "POST" {
		status, m := fail.Say(fail.BadRequest("request not POST"))
		http.Error(w, m, status)
		return
	}

	var payload struct {
		Name string        `json:"name"`
		Created *time.Time `json:"created"`
	}

	// JSON is hard, this will fail.
	if err := json.Decode(r.Request.Body, &payload); err != nil {
		var (
			m string
			status int
		)
		switch {
		case err == json.SyntaxError:
			status, m = fail.Say(fail.Cause(err).Unexpected())
		default:
			status, m = fail.Say(fail.Cause(err).BadRequest("your payload is terrible"))
		}
		http.Error(w, m, status)
		return
	}

	// if we manage to get this far, this will fail.
	if err := saveUserDB(&payload); err != nil {
		status, m := fail.Say(fail.Cause(err).Unexpected())
		http.Error(w, m, status)
		return
	}

	// Hah hah, this will fail.
	status, m := fail.Say(fail.Forbidden("resistance is futile."))
	http.Error(w, m, status)
})

Credits

Fail is Copyright (c) 2017 Codehack. Published under an MIT License

About

Manage and handle Go errors with nice and correct HTTP responses.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages