【问题标题】:What kind of errors are returned by HttpServer stream in DartDart 中的 HttpServer 流返回什么样的错误
【发布时间】:2020-11-28 06:35:32
【问题描述】:

我正在查看Dart server documentation。我知道我可以await for 一个这样的 HttpRequest:

import 'dart:io';

Future main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    4040,
  );
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    request.response.write('Hello, world!');
    await request.response.close();
  }
}

那是因为 HttpServer 实现了 Stream。但是由于流可以返回值或错误,所以我应该捕获这样的异常,对吧:

try {
  await for (HttpRequest request in server) {
    request.response.write('Hello, world!');
    await request.response.close();
  }
} catch (e) {
  // ???
}

但我不确定可以捕获什么样的异常。异常是来自请求(并保证 400 级响应)还是来自服务器(并保证 500 级响应)?还是两者兼有?

【问题讨论】:

    标签: dart exception dart-server


    【解决方案1】:

    错误状态代码

    在异常情况下,将设置 BAD_REQUEST 状态代码:

        } catch (e) {
          // Try to send BAD_REQUEST response.
          request.response.statusCode = HttpStatus.badRequest;
    

    (见source

    那就是 400(见 badRequest)。

    流错误

    In that same catch block,例外将是rethrown,这意味着您仍会收到流中的所有错误。这发生在processRequest 中,它处理bind 中的所有请求。
    您会在流中收到错误,因为它们是 forwarded to the sink in bind

    错误种类

    我只能找到一个显式异常类型:

        if (disposition == null) {
          throw const HttpException(
              "Mime Multipart doesn't contain a Content-Disposition header value");
        }
        if (encoding != null &&
            !_transparentEncodings.contains(encoding.value.toLowerCase())) {
          // TODO(ajohnsen): Support BASE64, etc.
          throw HttpException('Unsupported contentTransferEncoding: '
              '${encoding.value}');
        }
    

    (见source

    这些都是HttpExceptions

    【讨论】:

    • 非常有用!谢谢你。有趣的是,框架本身会尝试返回 BAD_REQUEST 并关闭响应。我在想我必须自己做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多