如何处理EJB中的异常?

时间:2014-11-28 09:41:30

标签: java-ee ejb

我编写了以下用于EJB异常处理的代码。

1)Module.java

`@WebService(serviceName = "Module")
@Stateless()
public class Module {
    /**
     * This is a sample web service operation
     */
    @WebMethod(operationName = "hello")
    public int hello(@WebParam(name = "name") String txt) throws Exception {
        int re=0;
        try{
            re=(6/0);     
        }catch(Exception e){
            throw (EJBException) new EJBException(se).initCause(e);
        }
        return re;;
        }
    }
}`

2) Client.jsp

`<%
try{
    selec.Module_Service service = new selec.Module_Service();
    selec.Module port = service.getModulePort();
    java.lang.String name = "";
    int result = port.hello(name);
    out.println("Result = "+result);
}catch(EJBException e){
    Exception ee=(Exception)e.getCause();
    if(ee.getClass().getName().equals("Exception")){
       System.out.println("Database error: "+ e.getMessage());
    }
}
%>`

内部catch块异常对象ee让我为null。 什么是它给我空值的问题

1 个答案:

答案 0 :(得分:2)

您没有使用推荐的方法从EJB检索根本原因异常。 EJBException#getCausedBy()是在EJB上获取根异常的推荐方法。

然而,根据API,如果从Throwable#getCause得到原因,情况会更好。所以你应该拥有的是

Exception ee= ((Throwable)e).getCause();