Skip to content

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

License

Notifications You must be signed in to change notification settings

caarlos0/httperr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

80 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

httperr

Build Status Coverage Status

I've been doing this in several different projects, I finally decided to convert it to a proper lib.

The idea is to add an error return to HTTP handler functions, so you can avoid writing if err != nil { http.Error(w, err); return } everywhere.

The basic usage looks like:

mux.Handle("/", httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
  err := doSomething()
  return err
}))

This will yield a 500 and return a JSON like {"error":"doSomething error"}.

The lib also provide a Wrap function, so you can decide which status code you want:

mux.Handle("/e", httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
  err := doSomething()
  return httperr.Wrap(err, http.StatusBadRequest)
}))

Or, you can throw errors with a status, e.g.:

mux.Handle("/e", httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
  if something {
  	return httperr.Errorf(http.StatusBadRequest, "something: %v", something)
  }
  return nil
}))

So, this is it! You can also check the examples folder for a "real" usage.

About

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

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages