When something goes wrong in a REST API, the client should receive a clear error with the right HTTP status, not a long stack trace. Spring Boot makes this straightforward with @ControllerAdvice.
Step 1: a custom exception
public class CourseNotFoundException extends RuntimeException {
public CourseNotFoundException(Long id) {
super("Course not found: " + id);
}
}
Throw it from the service layer when a lookup fails: repository.findById(id).orElseThrow(() -> new CourseNotFoundException(id)).
Step 2: a global handler
@RestControllerAdvice
public class ApiErrorHandler {
@ExceptionHandler(CourseNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> notFound(CourseNotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}
Every controller now returns a 404 with a short JSON message for this exception, without any try-catch in the controllers.
Step 3: validation errors
When a request body fails @Valid checks, Spring throws MethodArgumentNotValidException. Handle it in the same class, return 400 Bad Request, and list each field with its message. Front-end developers will thank you, because they can show the message next to the right input box.
Step 4: a safe fallback
Add a handler for Exception.class that returns 500 with a generic message, and log the real error on the server. Never send stack traces or database details to the client; they help attackers and confuse users.
Interview angle
Be ready to explain the difference between handling an exception inside one controller with @ExceptionHandler and globally with @ControllerAdvice, and why consistent error responses matter for API clients.
Related: Spring Boot: your first REST API, exception handling in Java and HTTP status codes.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
