Spring / Spring Boot 4 Basics Interview Questions
What is Spring Boot's exception handling with @RestControllerAdvice?
@RestControllerAdvice provides a centralised, global exception handling mechanism for all controllers. It replaces the need to put @ExceptionHandler methods in every controller class.
// Centralised exception handler: @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); // Handle custom domain exception: @ExceptionHandler(OrderNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFound(OrderNotFoundException ex) { return new ErrorResponse( "ORDER_NOT_FOUND", ex.getMessage(), Instant.now() ); } // Handle Bean Validation failures: @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorResponse handleValidation(MethodArgumentNotValidException ex) { Map<String, String> fieldErrors = ex.getBindingResult() .getFieldErrors() .stream() .collect(Collectors.toMap( FieldError::getField, FieldError::getDefaultMessage, (a, b) -> a // keep first on duplicate key )); return new ValidationErrorResponse("VALIDATION_FAILED", fieldErrors); } // Handle illegal argument: @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleIllegalArg(IllegalArgumentException ex) { return new ErrorResponse("INVALID_REQUEST", ex.getMessage(), Instant.now()); } // Catch-all for unexpected exceptions: @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ErrorResponse handleGeneral(Exception ex, HttpServletRequest request) { log.error("Unhandled exception for {}: {}", request.getRequestURI(), ex.getMessage(), ex); return new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred", Instant.now()); } } public record ErrorResponse(String code, String message, Instant timestamp) {}
More Related questions...