Another approach is to use @ExceptionHandler
with @ControllerAdvice
to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.
Your handler class:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyBadRequestException.class)
public ResponseEntity<MyError> handleException(MyBadRequestException e) {
return ResponseEntity
.badRequest()
.body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
}
}
Your custom exception:
public class MyBadRequestException extends RuntimeException {
private String description;
public MyBadRequestException(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.