VOOZH about

URL: https://www.javacodegeeks.com/2017/12/handle-custom-exception-types-jax-rs.html

⇱ Handle custom exception types in JAX-RS - Java Code Geeks


JAX-RS supports handling custom exceptions — thrown in either EJBs or CID 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 header Conflict-Reason: Could not greet.

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

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Handle custom exception types in JAX-RS

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
JAX-RS
👁 Photo of Sebastian Daschner
Sebastian Daschner
December 14th, 2017Last Updated: December 13th, 2017
0 76 1 minute read

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz