DEV Community

luthfisauqi17
luthfisauqi17

Posted on

Customizing 404 and 405 Error Responses in Golang Chi

When building a robust REST API with Golang, providing clear and consistent error responses is crucial for a good developer experience. By default, the Chi router provides standard text responses for missing routes or incorrect HTTP methods. However, you might want to return custom JSON or specific messages that align with your application's design.

In this guide, we will explore how to implement custom handlers for 404 Not Found and 405 Method Not Allowed using the Chi router.

1. Handling "404 Not Found"

A 404 error occurs when a user or client tries to access a route that hasn't been defined in your router.

To create a custom 404 handler, you need to define a standard http.HandlerFunc and then register it using r.NotFound.
The Handler:

func handleNotFound(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    w.Write([]byte("This route does not exist"))
}
Enter fullscreen mode Exit fullscreen mode

Registration:
Place this right after your router initialization:

r := chi.NewRouter()
r.NotFound(handleNotFound)
Enter fullscreen mode Exit fullscreen mode

Now, instead of the default browser or Chi message, the client will receive your custom string whenever they hit an undefined endpoint.

2. Handling "405 Method Not Allowed"

A 405 error happens when the endpoint exists, but the HTTP method used (e.g., POST instead of GET) is not supported by that specific route.

Similar to the 404 handler, you create a function and register it using r.MethodNotAllowed.

The Handler:

func handleMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusMethodNotAllowed)
    w.Write([]byte("Yo, this method is not allowed for this endpoint"))
}
Enter fullscreen mode Exit fullscreen mode

Registration:

r.MethodNotAllowed(handleMethodNotAllowed)
Enter fullscreen mode Exit fullscreen mode

Why Use Custom Handlers?

  1. Consistency: Ensure all your error responses follow the same format (e.g., always returning JSON).
  2. Branding/UX: You can provide more helpful messages or even redirect users to a documentation page.
  3. Debugging: You can log these specific errors more effectively within your custom handler logic.

Conclusion

The Chi router makes it incredibly simple to override default behaviors. By using r.NotFound() and r.MethodNotAllowed(), you gain full control over how your API communicates failures to the outside world.

Happy coding!

Top comments (0)