java / beginner
Snippet
Mapping Exceptions to HTTP Status Codes
Using @ResponseStatus on a custom exception class provides a simple way to return specific HTTP status codes when an error occurs.
snippet.java
1
2
3
4
5
6
@ResponseStatus(HttpStatus.BAD_REQUEST)public class InvalidInputException extends RuntimeException {public InvalidInputException(String message) {super(message);}}
spring
Breakdown
1
@ResponseStatus(HttpStatus.BAD_REQUEST)
Ensures a 400 Bad Request status is returned when this exception is thrown.
2
extends RuntimeException
Inherits from RuntimeException so it doesn't need mandatory catching.