I have a class
MyHttpAsyncHandler which implements
Once a request is received, it is handled via the
handle(HttpRequest, HttpAsyncExchange, HttpContext) method, which I have overridden:
HttpResponse response = httpExchange.getResponse(); response.setHeader("Content-Type", String.valueOf(ContentType.APPLICATION_JSON)); handleInternal(request, response, context); httpExchange.submitResponse(new BasicAsyncResponseProducer(response));
handleInternal method, after some processing, I define a
BasicHttpEntity and assign to it a class I've written which
extends BasicHttpEntity and
implements HttpAsyncContentProducer, like this:
BasicHttpEntity entity = new MyResultEntity(); // Setting the status as 200, since this is the default case. response.setStatusCode(HttpStatus.SC_OK); response.setEntity(entity);
Let's say that during the execution of the request, the "back-end" might end-up with an error.
produceContent, I can detect that error and I want to reply to the client with status code (500) and supply an informative error.
I have managed to supply an informative error, but I cannot manage to reply with a status code of 500.
Is there any way to do that?
What I have tried so far (and failed)
- Passing the
handleInternal to the constructor of
MyResultEntity, so as to set the status code using the setter. (Also, tried passing
HttpExchage, getting response and setting its status to 500 after content is ready.)
- Extending the
BasicAsyncResponseProducer (which contains the
response object) and during
produceContent detecting the error and setting the status code there.
It is also mentioned at the documentation that one can defer submission of response. How can one do this?
Am I missing something? Shouldn't there be a way to change the response's status code via the content producer if something goes wrong?
The packages I am using are these:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore-nio</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> </dependency>