Error handling is a critical aspect of any application, and having a robust mechanism for managing exceptions can significantly enhance the user experience. Spring Boot provides built-in support for exception handling, allowing you to create custom responses for specific exceptions. In this post, we will explore how to implement and manage custom exception handling in your Spring Boot applications.
Understanding Exception Handling in Spring Boot
Spring Boot utilizes the @ControllerAdvice
annotation to define a class that handles exceptions globally across the application. This allows for a consistent way of returning error messages and status codes.
Creating a Custom Exception
First, define a custom exception class for your application:
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
This custom exception can be thrown when a requested resource is not found.
Implementing Global Exception Handling
Create a global exception handler using the @ControllerAdvice
annotation:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Something went wrong: " + ex.getMessage());
}
}
In this example, the GlobalExceptionHandler
class defines how to handle the ResourceNotFoundException
and other general exceptions. This enables you to send back meaningful error messages along with the appropriate HTTP status codes.
Using Custom Exceptions in Controllers
Now let’s implement a sample controller that uses the custom exception:
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/resources")
public class ResourceController {
private Map<Long, String> resources = new HashMap<>();
public ResourceController() {
resources.put(1L, "Resource One");
resources.put(2L, "Resource Two");
}
@GetMapping("/{id}")
public String getResource(@PathVariable Long id) {
String resource = resources.get(id);
if (resource == null) {
throw new ResourceNotFoundException("Resource not found for id: " + id);
}
return resource;
}
}
Testing the Exception Handling
Run your Spring Boot application and test the API:
curl -X GET http://localhost:8080/api/resources/3
Since resource ID 3 does not exist, you should see a response with a 404 status code and your custom error message:
{ "status": 404, "message": "Resource not found for id: 3" }
Conclusion
Custom exception handling in Spring Boot allows you to create a more user-friendly API experience by providing meaningful error messages and appropriate HTTP status codes. This practice not only improves the robustness of your application but also helps clients understand and handle errors more effectively.
For further learning on advanced error handling strategies and best practices in Spring Boot, consider checking out the comprehensive resources offered by ITER Academy, designed to empower your development journey.