处理Spring Hibernate SQL错误的推荐方法 [英] Recommended way of dealing with spring hibernate SQL errors

查看:76
本文介绍了处理Spring Hibernate SQL错误的推荐方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a post endpoint in my controller in spring that looks like so

@Autowired
private BookRepository bookRepository;

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

现在,如果提交了无效的json数据并且调用了保存功能,我的控制台将输出诸如h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '1091209' for key 'isbn'

Now, if invalid json data is submitted and the save function is called my console will output an error such as h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '1091209' for key 'isbn'

用户将看到非常不友好的api响应.

And the user will see a very non-user friendly api response.

这带来的另一个问题似乎是跳过了一个auto_incremented id,例如我进入1,2,4,由于第3个api调用是失败的api调用,所以跳过了3.

Another issue this brings it seems is that an auto_incremented id is skipped e.g. I go 1,2,4, skipping 3 due the 3rd api call being the failing api call.

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

What is best practice for handling the above scenarios?

推荐答案

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

You can define your own error handler which extends ResponseEntityExceptionHandler and catch db specific exception. Here is a code...

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



}

这篇关于处理Spring Hibernate SQL错误的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆