Return value of RESTful Web Service, taking a null value into account

java, rest, unmarshalling

Solution

The idiomatic way to handle such situations is to return 404 Not Found response code. With jax-rs you can throw `WebApplicationException`:

@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
    Person personOrNull = people.byName(name);
    if(personOrNull == null) {
      throw new WebApplicationException(404);
    }   
    return personOrNull;
} 

Problem

I am creating a client to my RESTful Web Service. In this case, my Server will not always return the expected object (e.g. nothing found on a given parameter, so return is NULL). ``` @GET @Path("/person/{name}") @Produces("application/xml") public Person getPerson(@PathParam("name") String name) { return people.byName(name); } ``` The byName() method will return NULL if the given name is not found. Upon unmarshalling the given object, this will raise an exception. What is the most common and clean way to just result in an if/else statement or something to handle the returns in different ways? ``` JAXBContext jcUnmarshaller = JAXBContext.newInstance(Person.class); Unmarshaller unmarshaller = jcUnmarshaller.createUnmarshaller(); return (Person) unmarshaller.unmarshal(connection.getInputStream()); ``` SOLUTION ``` getPerson( ) throws WebApplicationException { throw new WebApplicationException(404); } ```

Original source