java - 处理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 调用。
处理上述情况的最佳做法是什么?
解决方案
您可以定义自己的错误处理程序,它扩展了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
}
}
推荐阅读
- php - PHP 7.2 停止写日志?
- css - Bootstrap 4.1.3 $font-family-base 被忽略
- java - 将多个微服务相互依赖部署到 docker 容器中
- c# - webhost respawn上的asp.net核心自托管应用程序泄漏
- mysql - Node Express MySql Sql 查询不起作用
- javascript - Object.getOwnPropertyDescriptors 不是函数
- ruby-on-rails - 如何在 Rails 模型中添加外键关联?
- c++ - MATLAB 由于 calllib(C++ .h 文件和 FORTRAN .dll)而崩溃
- javascript - 从 express-handlebars 获取数据到我的 javascript 文件
- docker - 如何减少构建上下文