O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Exceptions and Response Status Codes

Problem

You want your service to throw exceptions under certain conditions, and deal with them appropriately on the client.

Solution

Create a response with the status code you want to set, and then set it into a WebApplicationException instance and throw it out of the method.

Discussion

Example 8-30 shows the class that handles this.

Example 8-30. Creating an exception and setting your own HTTP status

package com.soacookbook.rest.response;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

@Path("statuscode")
public class CustomStatusCode {

    @GET
    public Response doGet(){
        Response.ResponseBuilder responseBuilder =                    
            Response.status(Response.Status.BAD_REQUEST);            
        Response response = responseBuilder.build();
        throw new WebApplicationException(response);
    }
}

The WebApplicationException is a runtime exception that you can use to issue clients standard HTTP response codes. The primary downside to the class is that it doesn’t allow you to set your own message. The default message and description will be sent with the exception to clients. In the case of BAD_REQUEST, there is no message, and the description is merely “The request sent by the client was syntactically incorrect ().” There’s no way that I’m aware of to change that message as of the current API, and still specify the response status directly using the WebApplicationException. You would think that something like ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required