mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
Export handling error response (#171)
This commit is contained in:
committed by
Travis Reeder
parent
5f206aa45b
commit
9ff3dc1d50
@@ -1,14 +1,16 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/Sirupsen/logrus"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/fnproject/fn/api/models"
|
||||
"github.com/fnproject/fn/api/runner/common"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ErrInternalServerError returned when something exceptional happens.
|
||||
@@ -19,15 +21,28 @@ func simpleError(err error) *models.Error {
|
||||
}
|
||||
|
||||
func handleErrorResponse(c *gin.Context, err error) {
|
||||
log := common.Logger(c.Request.Context())
|
||||
HandleErrorResponse(c.Request.Context(), c.Writer, err)
|
||||
}
|
||||
|
||||
// HandleErrorResponse used to handle response errors in the same way.
|
||||
func HandleErrorResponse(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
log := common.Logger(ctx)
|
||||
var statuscode int
|
||||
switch e := err.(type) {
|
||||
case models.APIError:
|
||||
if e.Code() >= 500 {
|
||||
log.WithFields(logrus.Fields{"code": e.Code()}).WithError(e).Error("api error")
|
||||
}
|
||||
c.JSON(e.Code(), simpleError(e))
|
||||
statuscode = e.Code()
|
||||
default:
|
||||
log.WithError(err).WithFields(logrus.Fields{"stack": string(debug.Stack())}).Error("internal server error")
|
||||
c.JSON(http.StatusInternalServerError, simpleError(ErrInternalServerError))
|
||||
statuscode = http.StatusInternalServerError
|
||||
err = ErrInternalServerError
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(statuscode)
|
||||
err = json.NewEncoder(w).Encode(simpleError(err))
|
||||
if err != nil {
|
||||
log.WithError(err).Errorln("error encoding error json")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user