首页 > 解决方案 > 如何从 SqlExceptionHelper 获取有关 REST spring 应用程序的错误信息

问题描述

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

例如:

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 );
            }
        }
    }

标签: springspring-bootspring-data-jpaspring-dataspring-data-rest

解决方案


学生表的“student_fkey_to_specialty”被违反。检查此约束是哪个字段,并为该字段提供正确的值


推荐阅读