Spring Data Rest异常处理-返回一般错误响应 [英] Spring Data Rest exception handling - Return generic error response
问题描述
我想知道由于格式错误的请求或数据库崩溃,如何处理Spring Data Rest中的内部服务器错误类型异常,例如JPA异常等。我进行了一些研究,发现更好的方法是使用@ControllerAdvice,但找不到任何可行的示例。我查看了这两个问题,但仍未得到解答。
I want to know how can I handle internal server error type exceptions in Spring Data Rest such as JPA exceptions etc. due to a malformed request or a database crash. I did some research found that the better way to do this is by using @ControllerAdvice but couldn't find any working example of it. I looked at both these questions but they are still unanswered.
如何使用Spring Data Rest和PagingAndSortingRepository处理异常?
有人在发生异常时如何使用@ControllerAdvice以及如何将自定义错误响应写回客户端的工作示例可以帮助我。
Can someone help me with a working example of how to use @ControllerAdvice and write a custom error response back to client whenever there is an exception.
推荐答案
您可以这样做:
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GenericExceptionHandler {
@ExceptionHandler
ResponseEntity handle(Exception e) {
return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
这篇关于Spring Data Rest异常处理-返回一般错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!