如何使用spring@controlleradvice和springweb处理hibernate异常

myzjeezk  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(385)

各位Maven大家好,
如何处理org.hibernate.exception.constraintviolationexception(以及所有其他hibernate异常)和runtimeexception以将以下json返回到前端?

{
    "timestamp": "2020-08-18T21:03:36.174Z",
    "code": "CODE_20500",
    "status": 500,
    "details": "An internal error occurred."
  }

实际上,我已经声明了我的控制器设备,并遵循了baeldung指南的步骤https://www.baeldung.com/problem-spring-web :

@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.0版本
实施“组织。zalando:problem-spring-web:0.23.0"
求求你,救命!谢谢您。

at0kjp5o

at0kjp5o1#

解决方案:
创建一个扩展abstractthrowableproblem的类“customexception”,并将自定义字段放在那里。对我来说是“代码”字段。
将下面的代码放入您的控制器设备:

@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

i5desfxk

i5desfxk2#

这是因为默认情况下,问题库将打印出异常类中包含的异常消息。
你可以做的是:
将对数据库的调用 Package 在try/catch子句中(以捕获hibernate异常),并重新抛出一个将隐藏不安全细节的自定义异常。
实施 ExceptionHandler 对于hibernate异常,以及将隐藏详细信息的自定义异常,请参阅此处的指南https://www.baeldung.com/exception-handling-for-rest-with-spring 解决方案1

相关问题