如何从SqlSpringHelper的REST Spring应用程序中获取有关错误的信息

问题描述 投票:0回答:3

我的数据库中有一些表,我想获取有关对数据库的错误请求的信息。如果我要保存带有错误外键的实体,我想获取有关这些键的详细信息。

例如:

2020-03-25 18:37:37.595 ERROR 9788 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: insert or update on table "student" violates foreign key constraint "student_fkey_to_specialty"
  Detail: Key (specialtykey)=(2) is not present in table "specialty".

我试图用这段代码解决,但我得到了其他信息。

could not execute statement; SQL [n/a]; constraint [student_fkey_to_specialty]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

我的代码:

@PostMapping
    public void saveStudent(@RequestBody StudentDTO studentDTO) {
        if(studentDTO!=null){
            try {
                studentService.save(studentDTO);

            }catch (Exception|Error e){
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getLocalizedMessage(),e );
            }
        }
    }
spring spring-boot spring-data-jpa spring-data spring-data-rest
3个回答
0
投票

学生表具有“ student_fkey_to_specialty”,这已被违反。检查此约束在哪个文件上,并为该字段提供正确的值


0
投票

我用这段代码解决了这个问题。这样可以从数据库中获取有关异常的信息。

e.getCause().getCause().getLocalizedMessage()

0
投票

使用循环迭代到原始异常,这是一个执行此操作的示例函数:

private String getCauseMessage(Throwable t)

    Throwable cause = t;
    while (t.getCause() != null) {
        cause = t.getCause();
    }

    return t.getLocalizedMessage();
}

由于您永远不知道可以将多少个异常链接在一起,因此使用循环是最安全的方法。如果您直接使用它,则可能会遇到NullPointerException或没有收到原始异常的消息。

© www.soinside.com 2019 - 2024. All rights reserved.