3

I have an endpoint that typically returns a document of type PDF, Word, etc. There is user input that goes along with this endpoint, however so I would like to validate it.

The trouble is, when I validate the input and want to return some sort of error JSON response, I end up getting errors similar to

Failed executing GET /foo/generateBar: NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: FooResponse of media type: application/octet-stream

What I am using on my endpoint is @Produces({"application/octet-stream", "application/json"})

Is there a way I can avoid this error by possibly returning both JSON and different file formats? My impression is that what the @Produces I was using was doing, however I'm probably thoroughly confused.

Additionally, I must note that I'm using window.open on the front-end side to call this endpoint.

Pretzel Pete
  • 41
  • 1
  • 1
  • 4
  • If you want to get JSON response from an endpoint that returns JSON and another type of response, you might want to try adding `accept: application/json` to the header of your request. – Verem Dugeri Dec 07 '18 at 05:42
  • @DanielVerem Programmatically, how would I do that in practice? Additionally, I must note that `window.open()` is being used on the frontend side to call this endpoint. – Pretzel Pete Dec 07 '18 at 15:58

2 Answers2

3

In Java and in javax.ws.rs.core.Response, you should try something like this in you headers:

               Response.status(response.getStatus())
                       .header("Accept", "application/json")
                       .header("Content-type", "application/json")
                       .entity(entity)
                       .build();
CodeSlave
  • 425
  • 6
  • 21
0

In order to solve this issue you have to consider the following aspects:

  1. Exceptions mangement

    Here you have to consider that each time you will have any exception you will throw custom exceptions and an exceptions handler will be implemented using @ControllerAdvice, or any other solution. This exceptions handler will return the response as a JSON.

  2. Handling to return the application/octet-stream

    To the endpoint, you need to mention that it will produce application/octet-stream. You can use: @GetMapping(produces = {MediaType.APPLICATION_OCTET_STREAM}).

  3. Provide to the GET request, the proper headers

    When you are calling the endpoint that produces the application/octet-stream you will add the Accept header with the value application/octet-stream, application/json. Now, in case of success, you'll receive the octet-stream and in case of any exception you'll receive the JSON response.

I hope this solution will help you!

Radu Linu
  • 1,143
  • 13
  • 29