TransWikia.com

What kind of errors are returned by HttpServer stream in Dart

Stack Overflow Asked by Suragch on December 23, 2020

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?

One 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.

Correct answer by creativecreatorormaybenot on December 23, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP