推荐的处理spring hibernate SQL错误的方法

我在spring的控制器中有一个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次api调用是失败的api调用而跳过3。

处理上述方案的最佳做法是什么?

您可以定义自己的error handling程序,该处理程序扩展ResponseEntityExceptionHandler并捕获特定于db的exception。 这是一个代码……

 @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 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 handleConstraintViolationException(SqlExceptionHelper ex) { // write your own logic to return user friendly response } }