Jax-RS(Jersey)上下文中WebApplicationException与WebServiceException之间的区别 [英] Difference between WebApplicationException and WebServiceException in the context of Jax-RS (Jersey)
问题描述
我正在创建一个泽西网络服务,我发现自己使用了所提到的异常类型。 WebServiceException的构造函数允许您传递一个String,作为WebApplicationException允许传入HTTP状态代码的原因。包括构造函数的差异,具有这两种异常类型的目的是什么?
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?
谢谢。
推荐答案
WebApplicationException是一种可以停止执行REST资源并发送一些有意义的信息的方法你的客户对于我一直在做的事情,我将此异常子类化,以便它具有将JSON作为错误消息生成到客户端的实现。在出现错误的情况下,让我们说一个丢失的文件,我可能会这样做:
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:
}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 '
WebServiceException是Jersey的根运行时间异常,即它的资源崩溃最常导致的结果是HTTP 500。
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.
< a href =http://download.oracle.com/javaee/5/api/javax/xml/ws/WebServiceException.html> http://download.oracle.com/javaee/5/api/javax/xml /ws/WebServiceException.html
所以简单的答案是第一个例外是一个你可能会抛出的,另一个是希望永远不会抛出的异常。 :P
So the short answer is the first exception is one you might throw and the other is one you hope is never thrown. :P
一个例子:
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); .... }});
这篇关于Jax-RS(Jersey)上下文中WebApplicationException与WebServiceException之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!