What is the purpose of @RestControllerAdvice in Spring Boot?
Answer:
Explanation:
The @RestControllerAdvice
annotation in Spring Boot is used to handle exceptions globally for REST controllers. It works similarly to @ControllerAdvice
, but is specifically designed for RESTful web services. When an exception is thrown in a REST controller, @RestControllerAdvice
can intercept it and provide a custom response.
Here’s an example of using @RestControllerAdvice
to handle exceptions globally:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
In this example, the @ExceptionHandler
methods inside the @RestControllerAdvice
class handle exceptions thrown by any REST controller in the application. The appropriate HTTP status and error message are returned to the client, ensuring consistent error handling across all REST endpoints.
Using @RestControllerAdvice
helps centralize and simplify exception handling, making your REST API more robust and easier to maintain.