如何处理基于ejb 3的soap webservice中的异常

时间:2011-01-31 10:20:30

标签: java web-services soap glassfish ejb-3.0

我目前正在开发基于EJB3的SOAP Web服务,我想知道处理未捕获异常的最佳实践是什么,并向客户端返回格式良好的SOAP响应。

示例:

@WebMethod
public SomeResponse processSomeService(
        @WebParam(name = "someParameters") SomeParameters someParameters)
{
     // the EJB do something with the parameters
     // and retrieve a response fot the client
     SomeResponse theResponse = this.doSomething(someParameters);

     return theResponse;
}

我是否必须捕获通用异常,如:

@WebMethod
public SomeResponse processSomeService(
        @WebParam(name = "someParameters") SomeParameters someParameters)
{
     // the EJB do something with the parameters
     // and retrieve a response to return to the client
     try
     {
         SomeResponse theResponse = this.doSomething(someParameters);
     }
     catch (Exception ex)
     {
         // log the exception
         logger.log(Level.SEVERE, "something is going wrong {0}", ex.getMessage());
         // get a generic error response not to let the
         // technical reason going to the client
         SomeResponse theResponse = SomeResponse.createError();
     }

     return theResponse;
}

为了达到这个目的,是否有某种“最佳实践”?

谢谢

3 个答案:

答案 0 :(得分:2)

在响应中返回错误不是一个好习惯,SOAP定义了一个SOAP错误来处理错误的返回。正如Michael Konietzka所指出的,容器可以处理抛出的异常并将其转换为SOAP错误。

在你的情况下,似乎你想先捕获并记录异常 - 抛出一个包装原始异常的新EJBException。

答案 1 :(得分:1)

如果要在发生错误时返回SOAP消息,则必须创建它。我不希望容器知道你需要什么。

我会说你的设计足够了。我所提出的一个批评是你不能具体说明错误的本质。

答案 2 :(得分:0)

无需捕获它们,ejb-container将处理此问题。

关于Alexandre GUIDET评论#1的更新

从EJB 3.1规范,第14.2.2节“异常处理 - >系统异常:

  • 如果bean方法遇到了 系统异常或错误,它应该 只是传播错误 容器的bean方法(即 bean方法不必 抓住例外)。

  • 如果bean方法执行了 导致检查的操作 bean方法不能的异常 恢复,bean方法应该抛出 包装的javax.ejb.EJBException 最初的例外。

  • 任何其他意外错误情况 应该报告使用 javax.ejb.EJBException异常。

因此,将RuntimeException传播到容器是EJB规范推荐的方式。