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

标签 java spring hibernate

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

相关文章:

java - 几个类之间的通信

java - 为什么 firePropertyChange(String propertyName, Object oldValue, Object newValue) protected 而不是公开的?

java - 使用递归找到所有可能的最长递增子序列

java - 如何在 Hibernate 中用 TableGenerator 替换已弃用的 MultipleHiLoPerTableGenerator

java - 带有 Hibernate 和 Spring 的通用 DAO,是不是比这更好的方法?

hibernate - 无法将工厂绑定(bind)到 JNDI 需要在环境或系统属性中指定类名

java - 无法自动连接[错误 : No matching bean of type]

java - Solr Faceting 计数降至零

spring - 如何使用 TestContainers + Spring Boot + oracle-xe

spring - org.hibernate.tool.schema.spi.CommandAcceptanceException : Error executing DDL via JDBC Statement in SpringBoot with h2 and JPA