EJB中如何处理异常?

4
我已经为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个回答

2
您没有使用推荐的方法来检索 EJB 的根本原因异常。获取 EJB 根异常的推荐方法是通过 EJBException#getCausedBy() 方法实现的。
然而,根据 API,如果您从 Throwable#getCause 中获取原因,甚至会更好。因此,您应该有以下内容:
Exception ee= ((Throwable)e).getCause();

将Throwable转换为类型是多余的。 - Steve C
我也这么认为,但出于某种原因,文档认为这样更好。我只是为了完整性而添加了该选项@SteveC - kolossus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接