Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 617
Menno Avatar asked Dec 27 '22 23:12

Menno


1 Answers

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;
} 
like image 168
Tomasz Nurkiewicz Avatar answered Mar 23 '23 01:03

Tomasz Nurkiewicz