java Jax-RS (Jersey) 上下文中 WebApplicationException 和 WebServiceException 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7959274/
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
Difference between WebApplicationException and WebServiceException in the context of Jax-RS (Jersey)
提问by Blaskovicz
I'm creating a Jersey web service, and I've found myself using both of the mentioned exception types. WebServiceException's constructor allows you to pass a String as the cause where WebApplicationException allows a HTTP status code to be passed in. Including constructor differences, what's the purpose of having these two exception types?
我正在创建一个 Jersey 网络服务,我发现自己使用了提到的两种异常类型。WebServiceException 的构造函数允许你传递一个 String 作为原因,其中 WebApplicationException 允许传入 HTTP 状态代码。包括构造函数的差异,拥有这两种异常类型的目的是什么?
Thanks.
谢谢。
回答by Gunnar Hoffman
A WebApplicationException is a way in which you may stop execution of a REST resource and send some meaningful information to your client. For the stuff I have been doing I subclassed this exception so that it has an implementation that produces JSON as error messages to the client. In the event of an error condition, let us say a missing file I might do something like this:
WebApplicationException 是一种您可以停止执行 REST 资源并向您的客户端发送一些有意义的信息的方式。对于我一直在做的事情,我将这个异常子类化,以便它有一个实现,可以将 JSON 作为错误消息生成给客户端。如果出现错误情况,假设文件丢失,我可能会执行以下操作:
}catch(FileNotFoundException ex){
throw new MyException(ex.getMessage());
On the client this then would produce something like:
在客户端,这将产生如下结果:
{ errorCode: 56, errorMessage: 'could not find file "input.txt"' };
http://download.oracle.com/javaee/6/api/javax/ws/rs/WebApplicationException.html'
http://download.oracle.com/javaee/6/api/javax/ws/rs/WebApplicationException.html'
A WebServiceException is the root run time exception for Jersey, i.e. its what most commonly results from your resources crashing and results in a HTTP 500.
WebServiceException 是 Jersey 的根运行时异常,即它最常见的原因是您的资源崩溃并导致 HTTP 500。
http://download.oracle.com/javaee/5/api/javax/xml/ws/WebServiceException.html
http://download.oracle.com/javaee/5/api/javax/xml/ws/WebServiceException.html
So the short answer is the first exception is one you might throw and the other is one you hope is never thrown. :P
所以简短的回答是第一个异常是你可能抛出的异常,另一个是你希望永远不会抛出的异常。:P
An example:
一个例子:
public class MyException extends WebApplicationException {
public MyException(JSONObject jsonObject) {
super(Response.status(Response.Status.OK)
.entity(jsonObject)
.type(MediaType.APPLICATION_JSON)
.build());
}
Then from anywhere in your code you want to halt execution and send the error information to the client do this:
然后从代码中的任何地方停止执行并将错误信息发送到客户端执行以下操作:
}catch(FileNotFoundException ex){
throw new MyException(new JSONObject(){{ this.put("errorCode", 4); .... }});