2

I am trying to create a response with responsebuilder. When I pass string in entity it works fine but when I pass some error class it doesnot works.

Here is code

1) Working fine

Response.status(400).entity("test").build();

2) Not working

Response.status(400).entity(new MyCustomExceptions(400,"My bad request")).build();

With above code I am getting error

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=text/plain

when I call this service with above code I am getting 500 error instead of 400.But in 1st case I am getting proper 400 error.

  • Just wanted to understand if I pass object to entity then do I need to override some methods in class MyCustomExceptions?
  • How response is created from MyCustomExceptions object?
  • If I pass string to entity it works fine.Why?
anand
  • 11,071
  • 28
  • 101
  • 159

2 Answers2

2

Mapping exceptions to HTTP error responses

JAX-RS allows you to define a direct mapping of Java exceptions to HTTP error responses.

By extending WebApplicationException, you can create application specific exceptions that build a HTTP response with the status code and an optional message as the body of the response.

With that in mind, instead of returning a Response, you could throw a BadRequestException which extends WebApplicationException and will be mapped to a HTTP response with the status code 400:

throw new BadRequestException("My bad request");

For more details regarding error handling in JAX-RS, refer to this answer.

Subclasses of WebApplicationException

For convenience, the WebApplicationException is currently extended by the following exceptions (and they can be extended to create your own exceptions):

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • I tried and it works but not able to understand as how throwing an exception returns a Response object. Any pointers will hellp. – anand Jan 23 '17 at 15:56
  • @Alien01 It's made by the JAX-RS runtime. I will add more details to my answer to make it clear. – cassiomolin Jan 23 '17 at 16:00
1

What is the value of accept parameter in HTTPHeader that you're passing? Looks like its text/plain and you're trying to return an Object.

  1. Pass the accept value as application/json in the request. OR
  2. Change your code in response to add type as Json/XML

    Response.status(400).type(MediaType.APPLICATION_JSON).entity(new MyCustomExceptions(400,"My bad request")).build();
    
Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
  • I changed to MediaType.APPLICATION_JSON , I did not get any error message but still did not get 400 error code. – anand Jan 23 '17 at 10:07
  • Are you sure? I got the response and with status as 400. Can you show how you're calling the service? – Kishore Bandi Jan 23 '17 at 10:11