首页 > 解决方案 > 处理spring hibernate SQL错误的推荐方式

问题描述

我在春天的控制器中有一个后端点,看起来像这样

@Autowired
private BookRepository bookRepository;

@PostMapping(path="/book")
public @ResponseBody BookEntity addBook(@RequestBody BookEntity bookEntity)
{
    return this.bookRepository.save(bookEntity);
}

现在,如果提交了无效的 json 数据并调用了 save 函数,我的控制台将输出错误,例如h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '1091209' for key 'isbn'

并且用户会看到一个非常不友好的 api 响应。

这带来的另一个问题似乎是跳过了 auto_incremented id,例如我去 1、2、4,跳过 3,因为第 3 个 api 调用是失败的 api 调用。

处理上述情况的最佳做法是什么?

标签: javahibernatespring-boot

解决方案


您可以定义自己的错误处理程序,它扩展了ResponseEntityExceptionHandler并捕获 db 特定异常。这是一个代码...

@RestControllerAdvice
@RequestMapping(produces = "application/json")
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    // This method handles constraint violation exception raised by DB. 
    // Similarly other type exceptions like custom exception and HTTP status related 
    //exception can be handled here.
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(ConstraintViolationException ex) {
    // write your own logic to return user friendly response 
   }

   // Below method is to handle _SqlExceptionHelper_ exception
    @ExceptionHandler(SqlExceptionHelper.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(SqlExceptionHelper ex) {
    // write your own logic to return user friendly response 
   }



}

推荐阅读