Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Handle Custom Exception Types in JAX-RS

DZone's Guide to

Handle Custom Exception Types in JAX-RS

Whether you're using EJBs or CDI beans, see how JAX-RS can help support handling custom exceptions to custom HTTP responses.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

JAX-RS supports handling custom exceptions — thrown in either EJBs or CDI beans — to custom HTTP responses.

Assuming we have an “exceptional” EJB:

@Stateless
public class Hello {

    public String greeting() {
        if (new Random().nextBoolean())
            throw new GreetingException("Could not greet");

        return "hello";
    }

}


@ApplicationException
public class GreetingException extends RuntimeException {

    public GreetingException(String message) {
        super(message);
    }

}


The EJB is used in our JAX-RS resource:

@Path("hello")
public class HelloResource {

    @Inject
    Hello hello;

    @GET
    public String hello() {
        return hello.greeting();
    }

}


Now, to map the occurring exception to a custom HTTP response, we can define a JAX-RS ExceptionMapper.

@Provider
public class GreetingExceptionMapper implements ExceptionMapper<GreetingException> {

    @Override
    public Response toResponse(GreetingException exception) {
        return Response.status(Response.Status.CONFLICT)
                .header("Conflict-Reason", exception.getMessage())
                .build();
    }

}


The exception mapper is registered as a JAX-RS extension (by @Provider) and will handle any GreetingException thrown by a resource method.

The example will occasionally output HTTP 409 Conflict with the header Conflict-Reason: Could not greet.

If a CDI-managed bean is used instead of an EJB, the @ApplicationException annotation is not required.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,exception handling ,jax-rs ,custom exceptions ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}