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

Default error page content-type to text/html #1535

Merged
merged 6 commits into from Jan 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 7 additions & 8 deletions errors.go
Expand Up @@ -140,24 +140,21 @@ type ErrorResponse struct {
Code int `json:"code" xml:"code,attr"`
}

const defErrorCT = "text/html; charset=utf-8"
const defaultErrorCT = "text/html; charset=utf-8"

type stackTracer interface {
StackTrace() errors.StackTrace
}

func defaultErrorHandler(status int, origErr error, c Context) error {
env := c.Value("env")
ct := defaults.String(httpx.ContentType(c.Request()), defErrorCT)
if strings.Contains(ct, "form") {
ct = defErrorCT
}
c.Response().Header().Set("content-type", ct)
requestCT := defaults.String(httpx.ContentType(c.Request()), defaultErrorCT)

c.Logger().Error(origErr)
c.Response().WriteHeader(status)

if env != nil && env.(string) == "production" {
c.Response().Header().Set("content-type", defaultErrorCT)
responseBody := productionErrorResponseFor(status)
c.Response().Write(responseBody)
return nil
Expand All @@ -171,8 +168,9 @@ func defaultErrorHandler(status int, origErr error, c Context) error {
}
trace = fmt.Sprintf("%s\n%s", origErr, strings.Join(log, "\n"))
}
switch strings.ToLower(ct) {
switch strings.ToLower(requestCT) {
case "application/json", "text/json", "json":
c.Response().Header().Set("content-type", "application/json")
err := json.NewEncoder(c.Response()).Encode(&ErrorResponse{
Error: errors.Cause(origErr).Error(),
Trace: trace,
Expand All @@ -182,6 +180,7 @@ func defaultErrorHandler(status int, origErr error, c Context) error {
return errors.WithStack(err)
}
case "application/xml", "text/xml", "xml":
c.Response().Header().Set("content-type", "text/xml")
err := xml.NewEncoder(c.Response()).Encode(&ErrorResponse{
Error: errors.Cause(origErr).Error(),
Trace: trace,
Expand All @@ -191,7 +190,7 @@ func defaultErrorHandler(status int, origErr error, c Context) error {
return errors.WithStack(err)
}
default:
c.Response().Header().Set("content-type", "text/html; charset=utf-8")
c.Response().Header().Set("content-type", defaultErrorCT)
if err := c.Request().ParseForm(); err != nil {
trace = fmt.Sprintf("%s\n%s", err.Error(), trace)
}
Expand Down
2 changes: 1 addition & 1 deletion errors_test.go
Expand Up @@ -52,7 +52,7 @@ func Test_defaultErrorHandler_XML(t *testing.T) {
res := w.XML("/").Get()
r.Equal(401, res.Code)
ct := res.Header().Get("content-type")
r.Equal("application/xml", ct)
r.Equal("text/xml", ct)
b := res.Body.String()
r.Contains(b, `<response code="401">`)
r.Contains(b, `<error>boom</error>`)
Expand Down