REST Exception Handling — Spring Technical Interview Questions & Answers
Returning clean JSON error responses.
REST Exception Handling
- REST apps should return clear JSON errors, not ugly stack traces to clients.
- Use @ControllerAdvice + @ExceptionHandler for global handling.
- Map exceptions to status codes (400 validation, 404 missing, 500 unexpected).
- Keep error payload consistent: message, code, timestamp.
- Centralize errors so every controller stays clean.
Technical Interview Tip: Global handler beats copy-paste try/catch in every method.
Code Examples for REST Exception Handling
REST Exception Handling — working example
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
Map<String, String> badRequest(IllegalArgumentException ex) {
return Map.of("error", ex.getMessage());
}
}
record CreateUserRequest(@NotBlank @Email String email) {}
@RestController
class Users {
@PostMapping("/users")
User create(@Valid @RequestBody CreateUserRequest req) {
return new User(req.email());
}
}REST Exception Handling — @RestControllerAdvice centralizes API errors; @Valid triggers bean validation on DTOs.
How to Explain REST Exception Handling to an Interviewer
What is REST Exception Handling (sb)?
Used for GET /api/marks/{roll} a campus API Not just the heading
Give one small example of REST Exception Handling (sb).
@RestController + service call Returning clean JSON error responses
What mistake do beginners make with REST Exception Handling (sb)?
business logic inside the controller Show the fix
Where do you use REST Exception Handling (sb)?
a campus API GET /api/marks/{roll}