Skip to content

Commit

Permalink
Return json on 500 error from API (go-gitea#11574)
Browse files Browse the repository at this point in the history
* add API specific InternalServerError()

Co-authored-by: zeripath <art27@cantab.net>

* return 500 error msg only if not Production mode

* Revert "return 500 error msg only if not Production mode"

This reverts commit 8467b2c.

* InternalServerError

Co-authored-by: zeripath <art27@cantab.net>
  • Loading branch information
2 people authored and Yohann Delafollye committed Jul 31, 2020
1 parent ee1d1a7 commit 6a01886
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions modules/context/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package context

import (
"fmt"
"net/http"
"net/url"
"strings"

Expand Down Expand Up @@ -64,18 +65,18 @@ type APINotFound struct{}
// swagger:response redirect
type APIRedirect struct{}

// Error responses error message to client with given message.
// Error responds with an error message to client with given obj as the message.
// If status is 500, also it prints error to log.
func (ctx *APIContext) Error(status int, title string, obj interface{}) {
var message string
if err, ok := obj.(error); ok {
message = err.Error()
} else {
message = obj.(string)
message = fmt.Sprintf("%s", obj)
}

if status == 500 {
log.Error("%s: %s", title, message)
if status == http.StatusInternalServerError {
log.ErrorWithSkip(1, "%s: %s", title, message)
}

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

// InternalServerError responds with an error message to the client with the error as a message
// and the file and line of the caller.
func (ctx *APIContext) InternalServerError(err error) {
log.ErrorWithSkip(1, "InternalServerError: %v", err)

var message string
if macaron.Env != macaron.PROD {
message = err.Error()
}

ctx.JSON(http.StatusInternalServerError, APIError{
Message: message,
URL: setting.API.SwaggerURL,
})
}

func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
page := NewPagination(total, pageSize, curPage, 0)
paginater := page.Paginater
Expand Down

0 comments on commit 6a01886

Please sign in to comment.