sebastiandaschner blog

Using JAX-RS exceptions for status codes

#jaxrs monday, december 04, 2017

One way to send specific HTTP (error) status codes from a JAX-RS resource is to use the class with its Builder Pattern-like API. If you want to specify the return type according to the response body, you can still do so and send a different status on errors by throwing a WebApplicationException.

public class TestResource {

    public String hello() {
        if (new Random().nextBoolean())
            throw new WebApplicationException(Response.Status.CONFLICT);

        return "Hello World, " +;


The constructors of this special type of exception accepts Responses, Response.Statuses or int types. The JAX-RS runtime will send the corresponding HTTP statuses and header fields, respectively.

There are also pre-defined subtypes of WebApplicationException for common errors like NotFoundException or BadRequestException.

This post was reposted from my newsletter issue 006


Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: