次の例のように、例外ハンドラを使用することができます。
@ControllerAdvice
public class ExceptionsHandler {
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<?> conflict(DataIntegrityViolationException e) {
return new ResponseEntity<>(new errorMsg(e.getRootCause().getMessage()), CONFLICT);
}
...
@Order(Ordered.HIGHEST_PRECEDENCE + 4)
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<?> handleNotFoundException(NotFoundException e) {
return new ResponseEntity<>(new errorMsg(e.getMessage()), NOT_FOUND);
}
...
@Order(Ordered.LOWEST_PRECEDENCE)
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception e) {
return new ResponseEntity<>(new errorMsg(e.getMessage()), INTERNAL_SERVER_ERROR);
}
}
便利なリソース:
Spring Boot - Error Handling
Exception Handling in Spring MVC
Error Handling for REST with Spring
を