gpt4 book ai didi

java - 在 Spring/Hibernate 中执行 CRUD 操作时抛出正确的异常

转载 作者:行者123 更新时间:2023-11-29 05:49:16 25 4
gpt4 key购买 nike

假设我正在尝试使用 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”

最佳答案

直接手动设置即可:

@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/Hibernate 中执行 CRUD 操作时抛出正确的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14613818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com