func errorHandler(ctx *Context) { if err := recover(); err != nil { ctx.APIError(500, "Internal Server Error", err) } } func main() { server := &http.Server{ ... } http.HandleFunc("/", handler) http.ListenAndServe(":8080", errorHandler(http.DefaultServeMux)) }
func handler(ctx *Context) { user, err := getUser(ctx.Params["id"]) if err != nil { ctx.APIError(404, "User Not Found", err) return } // do something with user... } func main() { server := &http.Server{ ... } http.HandleFunc("/users/:id", handler) http.ListenAndServe(":8080", nil) }In this example, we use the Context APIError middleware to handle an error that occurs when attempting to find a user. If the user is not found, we use the ctx.APIError method to return a 404 error response with an appropriate message. Overall, the Context APIError middleware is a useful library for handling errors in Go web applications. It helps to simplify the error handling process and provides a clean and consistent way to handle errors across the application.