java 在 JAX-WS 中抛出自定义异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3753174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:15:25  来源:igfitidea点击:

Throwing custom exceptions in JAX-WS

javajax-ws

提问by greycat

I have a JAX-WS web service with a web method that may throw an exception.

我有一个 JAX-WS Web 服务,其 Web 方法可能会引发异常。

@WebMethod
public Folder getTree() throws UnauthorizedException {
    //...
    // Get authorization data..
    //...
    if (!authorized) {
        throw new UnauthorizedException();
    }
    //...
}

It works all right if user is authorized, but when the exception is thrown it doesn't generate SOAP message with a fault, it just crashes web service with

如果用户获得授权,它可以正常工作,但是当抛出异常时,它不会生成带有错误的 SOAP 消息,它只会使 Web 服务崩溃

SEVERE: Unauthorized
    ru.cos.xdoc.storage.UnauthorizedException: Unauthorized
    at ru.cos.xdoc.storage.Storage.getTree(Storage.java:136)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    ...

and closes connection

并关闭连接

HTTP/1.1 500 Internal Server Error
X-Powered-By: Servlet/2.5
Server: Sun GlassFish Enterprise Server v2.1.1
Content-Type: text/xml;charset="utf-8"
Transfer-Encoding: chunked
Date: Mon, 20 Sep 2010 15:43:59 GMT
Connection: close  

I feel like I miss something simple

我觉得我错过了一些简单的事情

EDITThe problem has proven to arise only in the case an exception is thrown not long after the beginning of web method. When a delay is introduced before throwing an exception, like

编辑该问题已被证明仅在 Web 方法开始后不久引发异常的情况下才会出现。在抛出异常之前引入延迟时,例如

try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

throw new UnauthorizedException();

everything works fine.

一切正常。

Does anybody have a clue what may cause such a strange behaviour?

有没有人知道什么可能导致这种奇怪的行为?

回答by gpeche

Have you mapped your exception to a Fault? See JAX-WS - Map Exceptions to faults

您是否已将异常映射到故障?请参阅JAX-WS - 将异常映射到故障

回答by emas

maybe it would be simpler just to build a message telling "Permission denied", or something like that. In my opinion, a web service should never throw an exception, it should always return a response.

也许构建一条消息告诉“权限被拒绝”或类似的东西会更简单。在我看来,Web 服务不应该抛出异常,它应该始终返回响应。