Created
January 9, 2020 10:36
-
-
Save maruware/34327f5ea5cab4245c0ae72e612bad1c to your computer and use it in GitHub Desktop.
Go http error handle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
import ( | |
"fmt" | |
"net/http" | |
r "github.com/unrolled/render" | |
) | |
type ErrorResponse struct { | |
Code string `json:"code"` | |
} | |
func NewErrorResponse(code string) ErrorResponse { | |
return ErrorResponse{ | |
Code: code, | |
} | |
} | |
var render *r.Render = r.New() | |
func RenderError(w http.ResponseWriter, status int, v interface{}, err error) { | |
logger.Error(fmt.Errorf("responsed error: %+v", err)) | |
render.JSON(w, status, v) | |
} | |
func BadParameterError(w http.ResponseWriter, err error) { | |
body := NewErrorResponse("BadParameter") | |
RenderError(w, http.StatusBadRequest, body, err) | |
} | |
func UnexpectedError(w http.ResponseWriter, err error) { | |
body := NewErrorResponse("UnexpectedError") | |
RenderError(w, http.StatusBadRequest, body, err) | |
} | |
func NotfoundError(w http.ResponseWriter, err error) { | |
body := NewErrorResponse("Notfound") | |
RenderError(w, http.StatusNotFound, body, err) | |
} | |
func UnauthorizedError(w http.ResponseWriter, err error) { | |
body := NewErrorResponse("Unauthorized") | |
RenderError(w, http.StatusUnauthorized, body, err) | |
} | |
func ForbiddenError(w http.ResponseWriter, err error) { | |
body := NewErrorResponse("Forbidden") | |
RenderError(w, http.StatusForbidden, body, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment