0 day streak
java / beginner
Snippet

Handling Specific Controller Exceptions with ExceptionHandler

The @ExceptionHandler annotation in Spring catches and handles specific exceptions thrown by controller methods, converting errors into clean HTTP responses.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable Long id) {
if (id < 1) {
throw new IllegalArgumentException("User ID must be positive.");
}
return "User: " + id;
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleInvalidId(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
spring
Breakdown
1
if (id < 1) { throw new IllegalArgumentException(...); }
Checks validation logic and triggers an IllegalArgumentException if the ID is invalid.
2
@ExceptionHandler(IllegalArgumentException.class)
Specifies that this handler method intercepts any IllegalArgumentException within this controller.
3
return ResponseEntity.badRequest().body(ex.getMessage());
Constructs and returns an HTTP 400 (Bad Request) response containing the exception message.