Java 在Spring/Hibernate中执行CRUD操作时引发正确的异常
假设我试图使用hibernate将一个实体添加到表中,在添加到我的DAO之前,我检查它是否已经存在,如果已经存在,我将返回null对象,否则我将返回添加的实体IDJava 在Spring/Hibernate中执行CRUD操作时引发正确的异常,java,spring,hibernate,Java,Spring,Hibernate,假设我试图使用hibernate将一个实体添加到表中,在添加到我的DAO之前,我检查它是否已经存在,如果已经存在,我将返回null对象,否则我将返回添加的实体ID @ResponseBody @RequestMapping(method = RequestMethod.POST) public T addEntity(@RequestBody State state) { T response = null; try { response = getService
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public T addEntity(@RequestBody State state) {
T response = null;
try {
response = getService().add(state);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
但是当返回null时,我想显示正确的HTTP错误代码400,有没有办法在spring中这样做,而不是返回null?谢谢
编辑:
我试过这样的方法:
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public T addEntity(@RequestBody String message,
HttpServletResponse httpResponse) throws Exception {
T response = null;
try {
response = getService().add(message);
} catch (Exception e) {
httpResponse.setStatus(409);
e.printStackTrace();
throw new Exception("State already exists, Error 409");
}
return response;
}
但它给出了一个异常,因为“错误500状态已存在,错误409”您可以直接手动设置它:
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public T addEntity(@RequestBody State state, HttpServletResponse httpResponse) {
T response = null;
try {
response = getService().add(state);
} catch (Exception e) {
httpResponse.setStatus(400);
e.printStackTrace();
}
return response;
}
我认为这将是一个愚蠢的问题,与java有关,而不是与spring有关。因此,当从控制器调用add方法时,我会检查服务中的对象是否已经存在,如果存在,我会抛出错误409以避免冲突。抛出更具体的异常?创建一个类似DuplicateRecordException的异常子类,以便为其创建一个单独的catch块并设置代码谢谢我会解决它!您将行为从返回null更改为引发异常,因此情况有所不同。:)在这种情况下,将
@ExceptionHandler
与@ResponseStatus
一起使用,为什么不返回零而不是null?另一个选项是扩展协议并在rsponse中返回原因。您还可以在最新版本的spring中返回ResponseEntity。