【问题标题】:Changing httpresponse status on netty更改 netty 上的 httpresponse 状态
【发布时间】:2015-01-18 12:57:45
【问题描述】:

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 发送回客户端?

【问题讨论】:

  • 是的,就像我说的,只需构造一个 DefaultHttpResponse 并将其写回即可。

标签: http-headers netty


【解决方案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);

【讨论】:

  • 这样我得到的是客户端(浏览器)中的不完整错误
猜你喜欢
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 2021-08-03
  • 2021-11-25
相关资源
最近更新 更多