假设我正在尝试使用hibernate向表中添加一个实体,在添加我的DAO之前,我检查它是否已经存在,如果已经存在,则返回null对象,否则我返回添加的实体ID。
@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”
答案 0 :(得分:3)
您可以直接手动设置:
@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;
}