1/15
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
What types of exceptions can occur before, inside, and after a controller method?
Before controller → Request parsing fails (HttpMessageNotReadableException).
Inside controller → Business logic failure (UserNotFoundException).
After controller → Response serialization fails (HttpMessageNotWritableException).
What is the role of DispatcherServlet in exception handling?
Acts as a front controller, All exceptions will be bubbled up to DispatchServlet,
Pass to HandlerExceptionResolver chain
Looks for @ExceptionHandler (local/global).
If none → rethrow → container (Tomcat/Jetty) which returns a default error page or Spring Boot’s BasicErrorController at /error.
Difference between @ExceptionHandler in a controller (local) vs @ControllerAdvice globally?
@ExceptionHandler → local, only applies to one controller.
@ControllerAdvice / @RestControllerAdvice → global, applies to all controllers.
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
How can you Configure scope took a @ControllerAdvice?
Using attributes like basePackages, basePackageClasses, annotations, or assignableTypes.
@ControllerAdvice(
// apply only to controllers in package
basePackages = "com.example.api",
// apply to controllers in same package as given class
basePackageClasses = {UserController.class},
// apply only to controllers with this annotation
annotations = RestController.class,
// apply only to specific controller classes
assignableTypes = {AdminController.class}
Why we need to scope the @ControllerAdvice ??
But in large apps, we often want different rules for different domains or modules.
Example:
User API → errors should follow a UserApiError schema.
Admin API → errors should follow a stricter AdminError schema.
We can scope advice using attributes like:
@ControllerAdvice(basePackages = "com.example.api")
@ControllerAdvice(assignableTypes = {AdminController.class})
@ControllerAdvice(annotations = RestController.class)
✅ Why needed?
Microservices/monoliths with multiple modules (User, Admin, Payments) may each want their own error format.
Prevents one advice from unintentionally overriding others.
Helps in modular teams where each domain owns its own exception strategy.
How does @Order affect exception handlers?
Multiple advices may match a thrown exception.
Spring needs to know which one should win → that’s where @Order comes in.
Why needed?
Precedence control → ensures business/domain handlers run before generic fallback handlers.
Avoids overriding problem-specific handlers with generic ones.
Helps when mixing framework-level handling (ResponseEntityExceptionHandler) with custom business exceptions.
What is the best practices to define the order of the execptions ??
Business Advice (high priority) → Catches domain errors like UserNotFoundException.
Framework Advice (medium priority) → Extends ResponseEntityExceptionHandler for Spring MVC errors (validation, HTTP method not supported, etc.).
Fallback Advice (lowest priority) → Catches everything else (Exception.class).
This ensures:
Domain errors → handled first, with business-friendly schema.
Framework errors → standardized responses (400, 405, 415, etc.).
Unexpected errors → fallback JSON, no raw stack trace leaks.
What is ResponseEntityExceptionHandler and why extend it?
It’s an abstract Spring class that provides built-in handlers for common framework exception
Extending it allows you to customize standard error responses (validation errors, method not allowed, media type issues, etc.).
Covers all standard Spring MVC exceptions (400, 405, 415, etc.).
You only override what you need → no boilerplate.
Perfect for REST services that need consistency.
Common exceptions that ResponseEntityExceptionHandlerand handles?
MethodArgumentNotValidException → 400 Bad Request.
HttpRequestMethodNotSupportedException → 405 Method Not Allowed.
HttpMediaTypeNotSupportedException → 415 Unsupported Media Type.
NoHandlerFoundException → 404 Not Found.
What is the BasicErrorController?
Spring Boot’s default fallback controller mapped to /error
Last Resort: Handles any exception that was not resolved earlier.
Uses ErrorAttributes to populate error details (status, message, timestamp, path).
How can you customize Spring Boot Default Fallback Error Controller?
Override ErrorAttributes.
Implement your own ErrorController.
@ResponseStatus vs @ExceptionHandler
@ResponseStatus → simple mapping (exception → fixed status). Define it on a Exception Class
@ExceptionHandler → when you need dynamic error bodies or extra logic. → define it on Handler method
Q: Example?
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {}
vs
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ApiError> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(404).body(new ApiError("User not found"));
}
How do you structure exception handling in small vs large apps?
Small → One global @RestControllerAdvice extending ResponseEntityExceptionHandler.
Large → Split into domain advice, framework advice, and fallback advice, all returning a consistent schema.
What happens in Spring when a @Valid annotated request body fails validation?
It throws → MethodArgumentNotValidException
Override handleMethodArgumentNotValid in ResponseEntityExceptionHandler or use @ExceptionHandler(MethodArgumentNotValidException.class) to return a JSON with field → error message mapping.
What is Exception Propagation vs Translation
Propagation: Letting exceptions bubble up unchanged (e.g., throwing UserNotFoundException from service → controller).
Translation: Convert technical exceptions (SQLException) into domain-safe exceptions.
What is RFC 7807 Problem Details?
A standard JSON format for error responses ProblemDetail class