Handling exceptions in a REST service is crucial to ensure that the service returns meaningful error messages to the client in case of errors. Spring Boot provides several ways to handle exceptions in a REST service. In this blog post, we’ll be covering the steps to handle exceptions in a Spring Boot REST service using custom exceptions and @ControllerAdvice
.
Exception Handling
- Exception handling is an important aspect of any REST service.
- Spring Boot provides several ways to handle exceptions in a REST service.
- This article covers the steps to handle exceptions in a Spring Boot REST service using custom exceptions and
@ControllerAdvice
.
Define Custom Exceptions
- A custom exception class is created to represent errors in the application.
- The custom exception should extend
RuntimeException
. - Example:
class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
Use @ControllerAdvice
@ControllerAdvice
is used to handle exceptions globally across all controllers in the application.- The exception handler methods are annotated with
@ExceptionHandler
and specify the exception to be handled. - Example:
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse("Resource not found", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception ex) {
ErrorResponse error = new ErrorResponse("Server error", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Return Error Response
- In the exception handler methods, return an error response with a meaningful error message and the appropriate HTTP status code.
- Example error response:
class ErrorResponse {
private String error;
private String message;
public ErrorResponse(String error, String message) {
this.error = error;
this.message = message;
}
}
Raise Exceptions
- In the REST controllers, raise custom exceptions when errors occur.
- Example:
@GetMapping("/{id}")
public Resource getResourceById(@PathVariable("id") Long id) {
Resource resource = resourceService.getResourceById(id);
if (resource == null) {
throw new ResourceNotFoundException("Resource with id " + id + " not found");
}
return resource;
}
Conclusion
- Exception handling is an important aspect of any REST service.
- Spring Boot provides several ways to handle exceptions in a REST service.
- By using custom exceptions and
@ControllerAdvice
, you can handle exceptions globally and return meaningful error responses to the client.