goyave.dev/goyave/v5@v5.0.0-rc9.0.20240517145003-d3f977d0b9f3/status_handler.go (about) 1 package goyave 2 3 import ( 4 "net/http" 5 6 "goyave.dev/goyave/v5/validation" 7 ) 8 9 // StatusHandler is a regular handler executed during the finalization step of the request's lifecycle 10 // if the response body is empty but a status code has been set. 11 // Status handlers are mainly used to implement a custom behavior for user or server errors (400 and 500 status codes). 12 type StatusHandler interface { 13 Composable 14 Handle(response *Response, request *Request) 15 } 16 17 // PanicStatusHandler for the HTTP 500 error. 18 // If debugging is enabled, writes the error details to the response and 19 // print stacktrace in the console. 20 // If debugging is not enabled, writes `{"error": "Internal Server Error"}` 21 // to the response. 22 type PanicStatusHandler struct { 23 Component 24 } 25 26 // Handle internal server error responses. 27 func (*PanicStatusHandler) Handle(response *Response, _ *Request) { 28 response.error(response.GetError()) 29 if response.IsEmpty() && !response.Hijacked() { 30 message := map[string]string{ 31 "error": http.StatusText(response.GetStatus()), 32 } 33 response.JSON(response.GetStatus(), message) 34 } 35 } 36 37 // ErrorStatusHandler a generic status handler for non-success codes. 38 // Writes the corresponding status message to the response. 39 type ErrorStatusHandler struct { 40 Component 41 } 42 43 // Handle generic error reponses. 44 func (*ErrorStatusHandler) Handle(response *Response, _ *Request) { 45 message := map[string]string{ 46 "error": http.StatusText(response.GetStatus()), 47 } 48 response.JSON(response.GetStatus(), message) 49 } 50 51 // ValidationStatusHandler for HTTP 422 errors. 52 // Writes the validation errors to the response. 53 type ValidationStatusHandler struct { 54 Component 55 } 56 57 // Handle validation error responses. 58 func (*ValidationStatusHandler) Handle(response *Response, request *Request) { 59 errs := &validation.ErrorResponse{} 60 61 if e, ok := request.Extra[ExtraValidationError{}]; ok { 62 errs.Body = e.(*validation.Errors) 63 } 64 65 if e, ok := request.Extra[ExtraQueryValidationError{}]; ok { 66 errs.Query = e.(*validation.Errors) 67 } 68 69 message := map[string]*validation.ErrorResponse{"error": errs} 70 response.JSON(response.GetStatus(), message) 71 }