Apache CXF Webservices中的异常处理

Rev*_*thi 1 web-services cxf

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

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

import javax.jws.WebService;

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

}
Run Code Online (Sandbox Code Playgroud)
public String distrager throws Exception {
    int a  = 30;
    strategyData = "currentlyhadcoced" ;

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

    return strategyData;
}
Run Code Online (Sandbox Code Playgroud)

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

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你

Don*_*ows 6

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

如果你坚持使用可以抛出任何东西的低级API(它确实发生了;它确实发生了很多)那么你应该包装那个低级异常.这是一个简单的方法:

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

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

public String fooMethod(String example) throws ImplementationException {
    try {
        return doRealThingWith(example);
    } catch (Exception e) {
        throw new ImplementationException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

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