How do you create a custom error response in Spring Boot?
Table of Contents
Introduction
In a Spring Boot application, when exceptions occur, it’s crucial to send informative and structured error responses to the client. By default, Spring Boot provides some basic error messages for common HTTP errors (such as 404 or 500). However, for better control and clarity, you can define custom error responses.
Creating custom error responses allows you to structure error information (e.g., error code, message, timestamp) and ensure consistency across your application. This is especially useful in RESTful APIs, where consistent error handling can improve the client experience and make debugging easier.
This guide explains how to create and return custom error responses in a Spring Boot application by using @ControllerAdvice
and @ExceptionHandler
.
How to Create a Custom Error Response in Spring Boot
1. Define a Custom Error Response Class
The first step in creating a custom error response is to define a class that will structure the error details. This class can include fields such as errorCode
, message
, timestamp
, and details
.
Here is an example of a simple custom error response class:
In this example, ErrorResponse
includes the error code (errorCode
), a description (message
), additional details (details
), and the time when the error occurred (timestamp
). You can add more fields depending on your needs (e.g., path
, status
).
2. Create a Global Exception Handler Using @ControllerAdvice
In Spring Boot, you can use @ControllerAdvice
to create a global exception handler that can catch and process exceptions thrown by controllers. This approach helps centralize error handling logic and ensures consistency in error responses.
Here’s an example of a global exception handler that uses @ControllerAdvice
to handle exceptions globally and return a custom error response:
In this example:
- We handle general exceptions using
@ExceptionHandler(Exception.class)
and return a500 Internal Server Error
. - We handle a custom exception,
ResourceNotFoundException
, with a404 Not Found
status. - We also handle validation errors (
MethodArgumentNotValidException
) and return a400 Bad Request
status with detailed validation error messages.
3. Define Custom Exception Classes
You can create custom exception classes that will be used to throw specific errors in the application. For example:
This exception can be thrown in your application whenever a resource is not found (e.g., a missing database record or an unavailable resource). When thrown, the global exception handler will catch it and return a custom error response.
4. Example Controller with Custom Exceptions
Here’s an example of a controller that throws a custom exception (ResourceNotFoundException
) when a resource is not found:
In this example:
- If the resource with the specified
id
exists, it returns the resource. - If the resource is not found, it throws a
ResourceNotFoundException
, which is caught by the global exception handler, and a custom error response is returned to the client.
5. Customizing the HTTP Status Code
You can customize the HTTP status code along with the error response in the @ExceptionHandler
. The ResponseEntity
object allows you to specify both the response body and the HTTP status.
In this example, a 404 Not Found
status is returned along with the custom error message.
Practical Example
Example 1: Handling Different Types of Errors
Example 2: Validation Error Handling
Conclusion
Creating custom error responses in Spring Boot helps standardize how errors are communicated in your application, especially in REST APIs. By using @ControllerAdvice
and @ExceptionHandler
, you can handle exceptions globally, returning custom error messages, structured data, and appropriate HTTP status codes.
This approach ensures that error responses are consistent across all parts of the application, improves maintainability, and provides more informative feedback to clients when things go wrong.