Skip to content
This repository has been archived by the owner on Feb 24, 2024. It is now read-only.

Commit

Permalink
Merge pull request #138 from lumost/returnErrorCause
Browse files Browse the repository at this point in the history
UnWrap HttpErrors in pop middleware and return them.
  • Loading branch information
markbates authored Jan 16, 2017
2 parents ad7fa47 + 7a7f02e commit 8cb0a29
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
6 changes: 3 additions & 3 deletions default_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,13 @@ func (d *DefaultContext) Render(status int, rr render.Renderer) error {
bb := &bytes.Buffer{}
err := rr.Render(bb, data)
if err != nil {
return httpError{Status: 500, Cause: errors.WithStack(err)}
return HTTPError{Status: 500, Cause: errors.WithStack(err)}
}
d.Response().Header().Set("Content-Type", rr.ContentType())
d.Response().WriteHeader(status)
_, err = io.Copy(d.Response(), bb)
if err != nil {
return httpError{Status: 500, Cause: errors.WithStack(err)}
return HTTPError{Status: 500, Cause: errors.WithStack(err)}
}
return nil
}
Expand Down Expand Up @@ -155,7 +155,7 @@ func (d *DefaultContext) LogFields(values map[string]interface{}) {
}

func (d *DefaultContext) Error(status int, err error) error {
return httpError{Status: status, Cause: errors.WithStack(err)}
return HTTPError{Status: status, Cause: errors.WithStack(err)}
}

// Websocket returns an upgraded github.com/gorilla/websocket.Conn
Expand Down
5 changes: 3 additions & 2 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import (
"github.com/pkg/errors"
)

type httpError struct {
// HTTPError a typed error returned by http Handlers and used for choosing error handlers
type HTTPError struct {
Status int `json:"status"`
Cause error `json:"error"`
}

func (h httpError) Error() string {
func (h HTTPError) Error() string {
return h.Cause.Error()
}

Expand Down
8 changes: 6 additions & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"

"github.com/gorilla/mux"
"github.com/pkg/errors"
)

// Handler is the basis for all of Buffalo. A Handler
Expand Down Expand Up @@ -56,8 +57,11 @@ func (a *App) handlerToHandler(info RouteInfo, h Handler) http.Handler {

if err != nil {
status := 500
if e, ok := err.(httpError); ok {
status = e.Status
// unpack root cause and check for HTTPError
cause := errors.Cause(err)
httpError, ok := cause.(HTTPError)
if ok {
status = httpError.Status
}
eh := a.ErrorHandlers.Get(status)
err = eh(status, err, c)
Expand Down

0 comments on commit 8cb0a29

Please sign in to comment.