Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using streamoutput response in jersey,how to handle exception after I already flush some output?

Tags:

java

rest

jersey

recently I used the interface "StreamingOutput" in jersey to stream my json format response, for example:

@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public Response test(){
    StreamingOutput stream = new StreamingOutput() {

        @Override
        public void write(OutputStream os) throws IOException,
        WebApplicationException {
            Writer writer = new BufferedWriter(new OutputStreamWriter(os));
                for( ...  loop ...) {
                    //response something immediatly
                    writer.write(somthing ...);
                writer.flush();
            }
        }
    };

    return Response.ok(stream).build();
}   

But what if after I "//response something immediately" to client, some exception is thrown.

Beside just pending a special error message after part of normal response, is there any approach to handle this condition??

like image 826
柯鴻儀 Avatar asked Oct 02 '22 05:10

柯鴻儀


1 Answers

There is hardly anything you can do if there is an error while streaming. You can always catch the exception but the response already sent cannot be reverted. The classic case of this is the client receiving the stream suddenly became unavailable/aborted the download. At the best you can just log it.

like image 200
Santosh Avatar answered Oct 12 '22 11:10

Santosh