https://github.com/reecerussell/go-errors
A simple interface return descriptive errors from HTTP handlers.
https://github.com/reecerussell/go-errors
errors golang http
Last synced: 11 months ago
JSON representation
A simple interface return descriptive errors from HTTP handlers.
- Host: GitHub
- URL: https://github.com/reecerussell/go-errors
- Owner: reecerussell
- License: mit
- Created: 2021-10-05T17:14:21.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2021-10-15T10:05:59.000Z (over 4 years ago)
- Last Synced: 2024-06-20T06:26:56.555Z (almost 2 years ago)
- Topics: errors, golang, http
- Language: Go
- Homepage:
- Size: 7.81 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://goreportcard.com/badge/github.com/reecerussell/go-errors)
[](https://codecov.io/gh/reecerussell/go-errors)
[](https://godoc.org/github.com/reecerussell/go-errors)
# Errors
A simple interface return descriptive errors from HTTP handlers. Expanding on the `error` interface, `Error` provides APIs to set the `type` and `message` of the error, as well as an optional `paramName` property.
## Get started
It's super simple to integrate with your APIs, first all install the module into your project.
```
> go get -u github.com/reecerussell/go-errors
```
Then as an example, here's how you can use it in your handlers.
```go
import (
"net/http"
"github.com/reecerussell/go-errors/errors"
)
...
func myHandler(w http.ResponseWriter, r *http.Request) {
var data MyDataModel
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
// If the body is not valid, create a new validation error
// with a type. Then write it to the response with the helper.
err = errors.NewValidation(err).
SetType("invalid body")
errors.WriteResponse(w, err)
return
}
err = MyProcess(&data) // returns standard error
if err != nil {
// The WriteResponse helper can also write standard errors.
errors.WriteResponse(w, err)
}
}
```