In Go, handling errors in a web application's request/response cycle involves returning appropriate HTTP status codes and error responses to the client. Here are the steps to handle errors effectively in a Go web application:
type AppError struct {
Code int `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
}
func handleError(w http.ResponseWriter, err error) {
// Log the error
log.Println(err)
// Extract error details if available
code := http.StatusInternalServerError
message := err.Error()
if appErr, ok := err.(AppError); ok {
code = appErr.Code
message = appErr.Message
}
// Send error response to the client
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": map[string]interface{}{
"code": code,
"message": message,
},
})
}
func someHandler(w http.ResponseWriter, r *http.Request) {
// ...
// Example error handling when using some library or service
resp, err := someLibrary.SomeFunction()
if err != nil {
handleError(w, AppError{
Code: http.StatusInternalServerError,
Message: "Failed to perform operation.",
Details: err.Error(),
})
return
}
// ...
}
func errorHandlingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
handleError(w, AppError{
Code: http.StatusInternalServerError,
Message: "Internal Server Error.",
Details: fmt.Sprintf("%v", err),
})
}
}()
next.ServeHTTP(w, r)
})
}
By following these steps, you can handle errors effectively within the request/response cycle of a web application in Go.