小编典典

处理Spring Hibernate SQL错误的推荐方法

spring-boot

我在Spring在控制器中有一个发布端点,看起来像这样

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

处理上述情况的最佳实践是什么?


阅读 240

收藏
2020-05-30

共1个答案

小编典典

您可以定义自己的错误处理程序,该错误处理程序扩展了 ResponseEntityExceptionHandler
并捕获特定于数据库的异常。这是一个代码…

@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 
   }



}
2020-05-30