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

Better handle errors display as JSON or XML #1351

Merged
merged 3 commits into from
Oct 8, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package buffalo
import (
"database/sql"
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"sort"
Expand Down Expand Up @@ -131,6 +132,14 @@ func productionErrorResponseFor(status int) []byte {
return []byte(prodErrorTmpl)
}

// ErrorResponse is a used to display errors as JSON or XML
type ErrorResponse struct {
XMLName xml.Name `json:"-" xml:"response"`
Error string `json:"error" xml:"error"`
Trace string `json:"trace" xml:"trace"`
Code int `json:"code" xml:"code,attr"`
}

func defaultErrorHandler(status int, origErr error, c Context) error {
env := c.Value("env")
ct := defaults.String(httpx.ContentType(c.Request()), "text/html; charset=utf-8")
Expand All @@ -145,20 +154,29 @@ func defaultErrorHandler(status int, origErr error, c Context) error {
return nil
}

msg := fmt.Sprintf("%+v", origErr)
trace := fmt.Sprintf("%+v", origErr)
switch strings.ToLower(ct) {
case "application/json", "text/json", "json":
err := json.NewEncoder(c.Response()).Encode(map[string]interface{}{
"error": msg,
"code": status,
err := json.NewEncoder(c.Response()).Encode(&ErrorResponse{
Error: errors.Cause(origErr).Error(),
Trace: trace,
Code: status,
})
if err != nil {
return errors.WithStack(err)
}
case "application/xml", "text/xml", "xml":
err := xml.NewEncoder(c.Response()).Encode(&ErrorResponse{
Error: errors.Cause(origErr).Error(),
Trace: trace,
Code: status,
})
if err != nil {
return errors.WithStack(err)
}
default:
if err := c.Request().ParseForm(); err != nil {
msg = fmt.Sprintf("%s\n%s", err.Error(), msg)
trace = fmt.Sprintf("%s\n%s", err.Error(), trace)
}
routes := c.Value("routes")
if cd, ok := c.(*DefaultContext); ok {
Expand All @@ -167,7 +185,7 @@ func defaultErrorHandler(status int, origErr error, c Context) error {
}
data := map[string]interface{}{
"routes": routes,
"error": msg,
"error": trace,
"status": status,
"data": c.Data(),
"params": c.Params(),
Expand Down
38 changes: 38 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,44 @@ func Test_defaultErrorHandler_SetsContentType(t *testing.T) {
r.Equal("text/html; charset=utf-8", ct)
}

func Test_defaultErrorHandler_JSON(t *testing.T) {
r := require.New(t)
app := New(Options{})
app.GET("/", func(c Context) error {
return c.Error(401, errors.New("boom"))
})

w := httptest.New(app)
res := w.JSON("/").Get()
r.Equal(401, res.Code)
ct := res.Header().Get("content-type")
r.Equal("application/json", ct)
b := res.Body.String()
r.Contains(b, `"code":401`)
r.Contains(b, `"error":"boom"`)
r.Contains(b, `"trace":"`)
}

func Test_defaultErrorHandler_XML(t *testing.T) {
r := require.New(t)
app := New(Options{})
app.GET("/", func(c Context) error {
return c.Error(401, errors.New("boom"))
})

w := httptest.New(app)
res := w.XML("/").Get()
r.Equal(401, res.Code)
ct := res.Header().Get("content-type")
r.Equal("application/xml", ct)
b := res.Body.String()
r.Contains(b, `<response code="401">`)
r.Contains(b, `<error>boom</error>`)
r.Contains(b, `<trace>`)
r.Contains(b, `</trace>`)
r.Contains(b, `</response>`)
}

func Test_PanicHandler(t *testing.T) {
app := New(Options{})
app.GET("/string", func(c Context) error {
Expand Down