Apache CXF Web服务中的异常处理

时间:2011-11-03 04:28:34

标签: web-services cxf

我使用Apache CXF开发了一个Web服务,它将很快投入生产。 我担心此处的异常处理,我不确定我所遵循的是否正确。

我有一个如下所示的方法,我将我作为网络服务公开

import javax.jws.WebService;

@WebService
public interface TataWebService {
    public String distragery()throws Exception;

}
public String distrager throws Exception {
    int a  = 30;
    strategyData = "currentlyhadcoced" ;

    if(a==30) {
        throw new IncorrectProjectIdsException("The Value of a is 30");
    }

    return strategyData;
}

我定义用户定义异常的方式是这样的

@WebFault(name = "IncorrectProjectIdsDetails")    
public class IncorrectProjectIdsException extends Exception {

    private java.lang.String incorrectProjectIdsDetails;

    public IncorrectProjectIdsException (String message) {
        super(message);
    }

    public java.lang.String getFaultInfo() {
        return this.incorrectProjectIdsDetails;
    }
}

请告诉我这是否正确,关于方法签名中的throws声明还是shuld我们以任何其他方式处理?

非常感谢

1 个答案:

答案 0 :(得分:6)

您应该在接口中使用Exception注释@WebService的特定子类,以便JAX-WS引擎知道发布可能出现故障的信息。那是因为这是通过检查声明静态发现的信息,而不是动态发现实际抛出的异常。

如果你遇到了一个可以抛出任何东西的低级API(确实发生了;事实上,它发生了很多),那么你应该包装那个较低级别的异常。这是一种简单的方法:

@WebFault(name = "ImplementationFault")    
public class ImplementationException extends Exception {
    public ImplementationException(Exception cause) {
        super(cause.getMessage(), cause);
    }
}

你在网络方法中使用的是这样的:

public String fooMethod(String example) throws ImplementationException {
    try {
        return doRealThingWith(example);
    } catch (Exception e) {
        throw new ImplementationException(e);
    }
}

(还有其他方法可以进行异常映射,但它们要复杂得多。包装至少很简单。)