Skip to content

Commit ed64607

Browse files
authored
Return json on 500 error from API (#11574) (#11660)
Backport #11574 add API specific InternalServerError() InternalServerError
1 parent dc0ea13 commit ed64607

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

modules/context/api.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package context
77

88
import (
99
"fmt"
10+
"net/http"
1011
"net/url"
1112
"strings"
1213

@@ -64,18 +65,18 @@ type APINotFound struct{}
6465
// swagger:response redirect
6566
type APIRedirect struct{}
6667

67-
// Error responses error message to client with given message.
68+
// Error responds with an error message to client with given obj as the message.
6869
// If status is 500, also it prints error to log.
6970
func (ctx *APIContext) Error(status int, title string, obj interface{}) {
7071
var message string
7172
if err, ok := obj.(error); ok {
7273
message = err.Error()
7374
} else {
74-
message = obj.(string)
75+
message = fmt.Sprintf("%s", obj)
7576
}
7677

77-
if status == 500 {
78-
log.Error("%s: %s", title, message)
78+
if status == http.StatusInternalServerError {
79+
log.ErrorWithSkip(1, "%s: %s", title, message)
7980
}
8081

8182
ctx.JSON(status, APIError{
@@ -84,6 +85,22 @@ func (ctx *APIContext) Error(status int, title string, obj interface{}) {
8485
})
8586
}
8687

88+
// InternalServerError responds with an error message to the client with the error as a message
89+
// and the file and line of the caller.
90+
func (ctx *APIContext) InternalServerError(err error) {
91+
log.ErrorWithSkip(1, "InternalServerError: %v", err)
92+
93+
var message string
94+
if macaron.Env != macaron.PROD {
95+
message = err.Error()
96+
}
97+
98+
ctx.JSON(http.StatusInternalServerError, APIError{
99+
Message: message,
100+
URL: setting.API.SwaggerURL,
101+
})
102+
}
103+
87104
func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
88105
page := NewPagination(total, pageSize, curPage, 0)
89106
paginater := page.Paginater

0 commit comments

Comments
 (0)