Spring Exception on MVC

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/15

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

16 Terms

1
New cards

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).

2
New cards

What is the role of DispatcherServlet in exception handling?

Acts as a front controller, All exceptions will be bubbled up to DispatchServlet,

  1. Pass to HandlerExceptionResolver chain

    • Looks for @ExceptionHandler (local/global).

  2. If none → rethrow → container (Tomcat/Jetty) which returns a default error page or Spring Boot’s BasicErrorController at /error.

3
New cards

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

4
New cards

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}    

5
New cards

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.

6
New cards

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.

7
New cards

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:

  1. Domain errors → handled first, with business-friendly schema.

  2. Framework errors → standardized responses (400, 405, 415, etc.).

  3. Unexpected errors → fallback JSON, no raw stack trace leaks.

8
New cards

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.

9
New cards

Common exceptions that ResponseEntityExceptionHandlerand handles?

  • MethodArgumentNotValidException → 400 Bad Request.

  • HttpRequestMethodNotSupportedException → 405 Method Not Allowed.

  • HttpMediaTypeNotSupportedException → 415 Unsupported Media Type.

  • NoHandlerFoundException → 404 Not Found.

10
New cards

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).

11
New cards

How can you customize Spring Boot Default Fallback Error Controller?

  • Override ErrorAttributes.

  • Implement your own ErrorController.

12
New cards

@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"));
}

13
New cards

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.

14
New cards

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.

15
New cards

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.

16
New cards

What is RFC 7807 Problem Details?

A standard JSON format for error responses ProblemDetail class