更改netty上的httpresponse状态

时间:2015-01-15 05:17:56

标签: http-headers netty

api正在传输大量数据。在执行验证并打开与后端的连接然后创建jdbc语句之后,我们返回带有标头的httpresponse ok状态。我们看到的问题是,当流中断时,客户端不会收到错误代码,我们只能关闭通道。

以下是我们在开始时发回状态的方式;

HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
response.headers().set(CONTENT_TYPE, MimeTypes.TEXT_JSON_UTF_8);
response.setChunked(true);
response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED);
Channel ch = ctx.getChannel();
// Write the initial line and the header.
ch.write(response);

当流式传输过程中出现任何故障时,catch块会捕获错误;

} catch (Exception e) {
  ctx.getChannel().close();
  String msg = "Error while streaming dynamic content from backend datasource " + ((DatasetDynamic) datasets[0]).getDbDataSourceName();
  error(e, msg);
  debug("uriNodes=" + this.uriNodes + "; params=" + this.params);
  throw new Exception(msg, e);
} finally {

正如你在catch块中看到的那样,为了通知客户端,出了问题,它所做的只是; ctx.getChannel()。close();

无论如何我们可以将错误的httpresponse发送回客户端吗?

1 个答案:

答案 0 :(得分:1)

看起来你可以随时通过频道发送httpresponse,它不一定是标题;

    } catch (Exception e) {
  // Any exception here means an error in the middle of chunk streaming, we
  // send back http 500 to the client to inform the failure
  ResponseErrorStatus status = new ResponseErrorStatus(ServiceErrorStatus.INTERNAL_SERVER_ERROR,
        " error: " + e.getMessage() + (e.getCause() != null ? (" - caused by: " + e.getCause().getMessage()) : ""));
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status.serviceErrorStatus.httpStatus);
  Channel ch = ctx.getChannel();
  ch.write(response);