如何解决如何使用Spring @ControllerAdvice和problem-spring-web
您好Stackoverflow专家
我该如何处理org.hibernate.exception.ConstraintViolationException(以及所有其他休眠异常)和RuntimeException,将以下json返回到前端?
{
"timestamp": "2020-08-18T21:03:36.174Z","code": "CODE_20500","status": 500,"details": "An internal error occurred."
}
实际上,我已经声明了ControllerDevice并遵循了https://www.baeldung.com/problem-spring-web上的Baeldung Guide的步骤:
@ControllerAdvice
public class MyErrorHandlingControllerAdvice implements ProblemHandling {
}
我还在文件“ application.properties”中设置了这些属性
spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true
servlet.http.encoding.force=true
但是,当试图将重复的主键保存在数据库中时,我收到以下消息:
{
"timestamp": "2020-08-20T08:44:11.342+02:00","status": 400,"detail": "could not execute statement; SQL [n/a]; constraint [uq_mykatalog_name]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}
出于安全原因,我们无法将数据库字段公开。
我正在使用以下库版本:
springboot版本= 2.3.3发行
实现“ org.zalando:problem-spring-web:0.23.0”
请帮助! 谢谢。
解决方法
这是因为默认情况下,问题库将打印出包含在异常类中的异常消息。
您可以做的是:
- 在try / catch子句中包装对数据库的调用(以捕获Hibernate异常),然后重新抛出一个自定义异常,该异常将隐藏不安全的详细信息。
- 为休眠异常实施
ExceptionHandler
,并重新抛出将隐藏详细信息的自定义异常-请参见此处的指南https://www.baeldung.com/exception-handling-for-rest-with-spring解决方案1
解决方案:
-
创建一个扩展了AbstractThrowableProblem的类“ CustomException”,并将您的自定义字段放在此处。对我来说是“代码”字段。
-
在您的ControllerDevice中输入以下代码:
@ControllerAdvice
public class MyErrorHandlingControllerAdvice implements ProblemHandling {
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody CustomException onUnexpectedRuntimeException(RuntimeException e) {
return new CustomException("CODE_20500","An Internal error occurred.",INTERNAL_SERVER_ERROR);
}
}
它将处理扩展 RuntimeException 的任何异常,包括org.hibernate.exception.ConstraintViolationException
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。