【问题标题】:retrieve custom exception message in calling method在调用方法中检索自定义异常消息
【发布时间】:2012-06-20 18:20:28
【问题描述】:

我故意在 DAO 方法中将电子邮件设置为 null。它转到 DAO 类中持久方法中的异常块,我在自定义异常类中放置自定义错误消息“无法添加员工”; 如何在控制器中捕获该错误消息。如果我使用 e.getMessage() 在控制器异常块中获取整个消息,但我只想要自定义错误消息。

调用方法(控制器)


try {                  
    employeeDao.persist(employees);
}  
catch (SpringUtilException ex) {    
    System.out.println("..at line 87......."+ex.getErrorMessage());
}
catch (Exception e) {
    System.err.println("Exception returned message: " + e.getMessage());
}

调用方法(DAO)


public void persist(Employees employee) throws SpringUtilException {
    try {
        employee.setEmail(null);
        em.persist(employee);
    } 
    catch (EntityExistsException e) {
        throw new SpringUtilException(e, "Employee Duplicate");
    } 
    catch (Exception ex) {
        System.out.println("at line 31 in DAO..");
        throw new SpringUtilException("Failed to add Employee"); 
    }
}

【问题讨论】:

  • 你是从哪里得到 SpringUtilException 的?
  • 显示什么,你希望程序显示什么,SpringUtilException的代码是什么?
  • 它的普通自定义异常类。我发现它没有任何异常块,包括 DAO 方法中的异常块。我很困惑它的去向,但在控制器中它进入异常块。
  • 即使在控制台中收到以下错误消息,但它不会进入 DAO 方法中的任何错误异常块。我使用 JPA 在数据库中插入数据。[EL Fine]:2012-06-20 15 :42:54.661--ClientSession(18324508)--Connection(10989057)--INSERT INTO EMPLOYEES (EMPLOYEE_ID, EMAIL, FIRST_NAME, HIRE_DATE, JOB_ID, LAST_NAME, SALARY, CITY, STATE, ZIP) 值 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) bind => [277, null, ET, 2011-11-11, AD_VP, ETE, 11, null, null, null] 不能将 NULL 插入 ("HR" ."EMPLOYEES"."EMAIL")
  • 停止在你的控制器中捕获异常,或者至少在异常上调用 e.printStackTrace() ,以了解抛出了哪个异常。然后向我们展示堆栈跟踪。而且 getErrorMessage() 不是标准的 Exception 方法,所以无法猜测它能做什么。

标签: java jsp spring-mvc


【解决方案1】:

em.persist() 只是使瞬态实体持久化。它不发出任何插入语句。

导致您获得异常的插入语句在刷新时发出。并且刷新是在事务结束时完成的(在这种情况下),此时 DAO 方法已经返回。

不要依赖数据库约束来验证您的对象。明确地验证它们,如果实体无效,甚至不要调用persist()。数据库约束是最后的检查。

【讨论】:

  • 再次测试将employee设置为null,这次第25和33行打印在控制台中。为什么它进入Exception块而不是Controller中的SpringUtilException块。 System.out.println("在 DAO 的第 25 行..");员工=空; em.persist(员工); System.out.println("在 DAO 的第 28 行.."); } catch (EntityExistsException e) { System.out.println("在 DAO 的第 30 行.."); throw new SpringUtilException(e, "Employee Duplicate"); } catch (Exception ex) { System.out.println("at line 33 in DAO.."); throw new SpringUtilException("添加员工失败"); }
  • 您已被要求两次发布异常的堆栈跟踪。我已经解释了为什么你在我的回答中没有得到 SpringUtilException 。阅读答案和 cmets 而不是忽略它们。
  • DAO 中的第 25 行.. DAO 中的第 33 行.. 错误:org.springframework.transaction.interceptor.TransactionInterceptor - 应用程序异常被提交异常 com.kesava.tutorial.util.SpringUtilException 覆盖com.kesava.tutorial.dao.EmployeeDAO.persist(EmployeeDAO.java:38) org.springframework.transaction.TransactionSystemException:无法提交 JPA 事务;嵌套异常是 javax.persistence.RollbackException: Transaction roll back because transaction was set to RollbackOnly.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多