java / beginner
Snippet
Binding Custom Exceptions to HTTP Statuses with ResponseStatus
The @ResponseStatus annotation maps a custom Java exception directly to an HTTP response status code. When this exception is thrown from any controller method without explicit handling, Spring automatically converts it to the specified HTTP response.
snippet.java
java
1
2
3
4
5
6
7
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource does not exist")public class ResourceNotFoundException extends RuntimeException {public ResourceNotFoundException(String message) {super(message);}}
spring
Breakdown
1
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource does not exist")
Instructs Spring Web to return an HTTP 404 status code and an error reason message whenever this exception propagates.
2
public class ResourceNotFoundException extends RuntimeException {
Declares an unchecked custom exception extending RuntimeException.
3
super(message);
Passes the detailed error message string to the superclass constructor.