【问题标题】:Recommended way of dealing with spring hibernate SQL errors处理spring hibernate SQL错误的推荐方式
【发布时间】:2023-04-10 15:34:01
【问题描述】:

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

@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 调用。

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

【问题讨论】:

标签: java hibernate spring-boot


【解决方案1】:

您可以定义自己的错误处理程序,它扩展了 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 
   }



}

【讨论】:

  • 您不能将 SqlExceptionHelper.class 传递给 @ExceptionHandler 注释,因为它不是 Throwable。
猜你喜欢
  • 2020-12-20
  • 2015-11-18
  • 1970-01-01
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2012-08-25
  • 1970-01-01
相关资源
最近更新 更多