Dart 中的 HttpServer 流返回什么样的错误

What kind of errors are returned by HttpServer stream in Dart

我正在检查 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。但是由于流可以 return 一个值或一个错误,我应该像这样捕获异常,对吧:

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

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

错误状态代码

出现异常时,将设置 BAD_REQUEST 状态码:

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

(参见source

那就是 400(参见 badRequest)。

流错误

In that same catch block, the exceptions will be rethrown, which means that you will still receive all the errors on your stream. This happens in 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