VOOZH about

URL: https://www.javacodegeeks.com/2017/12/using-jax-rs-exceptions-status-codes.html

⇱ Using JAX-RS exceptions for status codes - Java Code Geeks


One way to send specific HTTP (error) status codes from a JAX-RS resource is to use the javax.ws.rs.core.Response 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.

@Path("test")
public class TestResource {

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

 return "Hello World, " + Instant.now();
 }

}

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.

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Using JAX-RS exceptions for status codes

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 7th, 2017Last Updated: December 6th, 2017
0 137 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