Spring Boot simplify the exception handling a lot.
There are 2 ways to handle the exception, first one is controller base, we define the exceptions in the controller:
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")
public class OrderNotFoundException extends RuntimeException {
// ...
}
@RequestMapping(value="/orders/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Order order = orderRepository.findOrderById(id);
if (order == null) throw new OrderNotFoundException(id);
model.addAttribute(order);
return "orderDetail";
}
Another solution is the global exception handling, we used @ControllerAdvice to apply the @ExceptionHandler to the whole application.
On top of that, we could use the Problem Framework to specify the standardized error format for your application.
@ControllerAdvice
public class SpringExceptionHandlerAdvice implements ProblemHandling {
@ExceptionHandler
public ResponseEntity<Problem> handleFooException(final FooException exception, final NativeWebRequest request) {
final var problemBuilder = Problem.builder().withStatus(Status.BAD_REQUEST).withTitle("Foo Exception");
final var problem = getProblem(exception.getBindingResult(), problemBuilder);
return new ResponseEntity<>(problem, HttpStatus.BAD_REQUEST);
}
}