github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/api/admin/errors.go (about) 1 package admin 2 3 import ( 4 "net/http" 5 6 "github.com/go-chi/render" 7 validation "github.com/go-ozzo/ozzo-validation" 8 ) 9 10 // ErrResponse renderer type for handling all sorts of errors. 11 type ErrResponse struct { 12 Err error `json:"-"` // low-level runtime error 13 HTTPStatusCode int `json:"-"` // http response status code 14 15 StatusText string `json:"status"` // user-level status message 16 AppCode int64 `json:"code,omitempty"` // application-specific error code 17 ErrorText string `json:"error,omitempty"` // application-level error message, for debugging 18 ValidationErrors validation.Errors `json:"errors,omitempty"` // user level model validation errors 19 } 20 21 // Render sets the application-specific error code in AppCode. 22 func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error { 23 render.Status(r, e.HTTPStatusCode) 24 return nil 25 } 26 27 // ErrInvalidRequest returns status 422 Unprocessable Entity including error message. 28 func ErrInvalidRequest(err error) render.Renderer { 29 return &ErrResponse{ 30 Err: err, 31 HTTPStatusCode: http.StatusUnprocessableEntity, 32 StatusText: http.StatusText(http.StatusUnprocessableEntity), 33 ErrorText: err.Error(), 34 } 35 } 36 37 // ErrRender returns status 422 Unprocessable Entity rendering response error. 38 func ErrRender(err error) render.Renderer { 39 return &ErrResponse{ 40 Err: err, 41 HTTPStatusCode: http.StatusUnprocessableEntity, 42 StatusText: "Error rendering response.", 43 ErrorText: err.Error(), 44 } 45 } 46 47 // ErrValidation returns status 422 Unprocessable Entity stating validation errors. 48 func ErrValidation(err error, valErr validation.Errors) render.Renderer { 49 return &ErrResponse{ 50 Err: err, 51 HTTPStatusCode: http.StatusUnprocessableEntity, 52 StatusText: http.StatusText(http.StatusUnprocessableEntity), 53 ErrorText: err.Error(), 54 ValidationErrors: valErr, 55 } 56 } 57 58 var ( 59 // ErrBadRequest return status 400 Bad Request for malformed request body. 60 ErrBadRequest = &ErrResponse{HTTPStatusCode: http.StatusBadRequest, StatusText: http.StatusText(http.StatusBadRequest)} 61 62 // ErrNotFound returns status 404 Not Found for invalid resource request. 63 ErrNotFound = &ErrResponse{HTTPStatusCode: http.StatusNotFound, StatusText: http.StatusText(http.StatusNotFound)} 64 65 // ErrInternalServerError returns status 500 Internal Server Error. 66 ErrInternalServerError = &ErrResponse{HTTPStatusCode: http.StatusInternalServerError, StatusText: http.StatusText(http.StatusInternalServerError)} 67 )