Skip to content

Commit

Permalink
Added docs for using EnableHTTPStatusErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
Calvin Lobo committed Sep 14, 2023
1 parent 30fa96f commit e6f0407
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,10 @@ simplerr.Formatter = func(e *simplerr.SimpleError) string {
## HTTP Status Codes

HTTP status codes can be set automatically by using the [ecosystem/http](https://github.com/lobocv/simplerr/tree/master/ecosystem/http)
package to translate `simplerr` error codes to HTTP status codes. To do so, you must use the `simplehttp.Handler` or
package to translate `simplerr` error codes to HTTP status codes and vice versa.

### Converting SimpleError to HTTP status codes
To do so, you must use the `simplehttp.Handler` or
`simplehttp.HandlerFunc`instead of the ones defined in the `http` package. The only difference between the two is that
the `simplehttp` ones return an error.
Adapters are provided in order to interface with the `http` package. These adapters call `simplehttp.SetStatus()` on the returned
Expand Down Expand Up @@ -282,6 +285,15 @@ func main() {
}
```

### Converting HTTP status codes to SimpleError

The standard library `http.DefaultTransport` will return all successfully transported request/responses without error.
However, most applications will react to those responses by looking at the HTTP status code. From the application's point
of view, `4XX` and `5XX` series statuses **are errors**.
In order to get your HTTP clients to return `SimpleError` for `4XX` and `5XX` series errors, you can wrap their `http.RoundTripper`
using `simplehttp.EnableHTTPStatusErrors(rt http.RoundTripper)`.
## GRPC Status Codes
Since GRPC functions return an error, it is even convenient to integrate error code translation using an interceptor (middleware).
Expand Down
1 change: 1 addition & 0 deletions ecosystem/http/roundtripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type roundTripper struct {
rt http.RoundTripper
}

// RoundTrip calls the underlying RoundTripper and converts any 4XX or 5XX series errors to SimpleErrors
func (s roundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
resp, err := s.rt.RoundTrip(request)
if err != nil {
Expand Down

0 comments on commit e6f0407

Please sign in to comment.