Export handling error response (#171)

This commit is contained in:
James Jeffrey
2017-07-28 11:05:30 -07:00
committed by Travis Reeder
parent 5f206aa45b
commit 9ff3dc1d50

View File

@@ -1,14 +1,16 @@
package server package server
import ( import (
"context"
"encoding/json"
"errors" "errors"
"net/http" "net/http"
"runtime/debug" "runtime/debug"
"github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/fnproject/fn/api/models" "github.com/fnproject/fn/api/models"
"github.com/fnproject/fn/api/runner/common" "github.com/fnproject/fn/api/runner/common"
"github.com/gin-gonic/gin"
) )
// ErrInternalServerError returned when something exceptional happens. // ErrInternalServerError returned when something exceptional happens.
@@ -19,15 +21,28 @@ func simpleError(err error) *models.Error {
} }
func handleErrorResponse(c *gin.Context, err 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) { switch e := err.(type) {
case models.APIError: case models.APIError:
if e.Code() >= 500 { if e.Code() >= 500 {
log.WithFields(logrus.Fields{"code": e.Code()}).WithError(e).Error("api error") log.WithFields(logrus.Fields{"code": e.Code()}).WithError(e).Error("api error")
} }
c.JSON(e.Code(), simpleError(e)) statuscode = e.Code()
default: default:
log.WithError(err).WithFields(logrus.Fields{"stack": string(debug.Stack())}).Error("internal server error") 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")
} }
} }