Difference between WebApplicationException and WebServiceException in the context of Jax-RS (Jersey)

16,403

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'

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.

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

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); .... }});
Share:
16,403

Related videos on Youtube

Blaskovicz
Author by

Blaskovicz

I'm an avid web site/service programmer with a knowledge of golang, javascript, ruby, unix, html, css, scss, perl, and a passion for automation.

Updated on June 04, 2022

Comments

  • Blaskovicz
    Blaskovicz almost 2 years

    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?

    Thanks.

  • Blaskovicz
    Blaskovicz over 12 years
    So if I were to want to do something similar with WebApplicationException like return a json or xml response, how would I do that?
  • Gunnar Hoffman
    Gunnar Hoffman over 12 years
    @Blaskovicz posted an example above for you. Does this fully answer your question?
  • heyomi
    heyomi about 11 years
    Will this code be able to return a json formatted error to the client?
  • Cosmin Cosmin
    Cosmin Cosmin almost 11 years
    what does WebServiceException have to do with JAX-RS ? it's used in JAX-WS !
  • enfany
    enfany almost 10 years
    Will this cause the logging framework to create an exception stack trace?