What kind of errors are returned by HttpServer stream in Dart

143 views Asked by At

I'm going through the Dart server documentation. I see I can await for an HttpRequest like this:

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();
  }
}

That's because HttpServer implements Stream. But since a stream can return either a value or an error, I should catch exceptions like this, right:

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

But I'm not sure what kind of exceptions can be caught. Do the exceptions arise from the request (and warrant a 400 level response) or from the server (and warrant a 500 level response)? Or both?

1

There are 1 answers

1
creativecreatorormaybenot On BEST ANSWER

Error status codes

On exception, a BAD_REQUEST status code will be set:

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

(see source)

That would be 400 (see badRequest).

Stream errors

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, which processes all requests in bind.
And you get the errors on your stream because they are forwarded to the sink in bind.

Kinds of errors

I could only find a single explicit exception type:

    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}');
    }

(see source)

These are both HttpExceptions.