0 day streak
java / beginner
Snippet

Custom Errors with @ResponseStatus

By using @ResponseStatus on a custom exception class, you can define which HTTP status code should be sent to the client when that exception is thrown.

snippet.java
java
1
2
3
4
5
6
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
spring
Breakdown
1
@ResponseStatus(...)
Specifies the HTTP status code (404 Not Found) to be returned when this exception is thrown.
2
extends RuntimeException
Custom exceptions in Spring typically extend RuntimeException for unchecked behavior.