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) {}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
