1

假设我正在尝试使用休眠将实体添加到表中,在添加我的 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”

4

1 回答 1

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;

}
于 2013-01-30T21:26:17.703 回答