spring-data:如何拦截返回4xx,5xx的api /应用程序特定错误消息?
弹簧数据休息: 在不使用spring控制器的情况下,我找不到拦截sql错误/异常并向API调用者返回更有意义的消息的方法。
答案 0 :(得分:0)
您可以使用异常处理程序,例如:
@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