JuniorJunior (1–3 yrs)CodingJavaSpring BootOracleAmazonInfosys
RestController advice
How do you centralize exception handling in Spring Boot?
Answers use simple, clear English.
Quick interview answer
Use @ControllerAdvice / @RestControllerAdvice with @ExceptionHandler methods to map exceptions to consistent Problem Details / error DTOs. Keep domain exceptions meaningful; avoid leaking stack traces to clients.
Detailed answer
Use @ControllerAdvice / @RestControllerAdvice with @ExceptionHandler methods to map exceptions to consistent Problem Details / error DTOs. Keep domain exceptions meaningful; avoid leaking stack traces to clients.
Code example
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
Map<String,String> notFound(NotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}Practice code · java (view only · no execution)
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
Map<String,String> notFound(NotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}#spring#api