What's the recommended way in Dart: asserts or throw Errors

前端 未结 4 881
攒了一身酷
攒了一身酷 2021-01-11 16:25

Dart explicitly makes a distinction between Error, that signals a problem in your code\'s logic and should never happen and should never be caught and Exceptions that signal

4条回答
  •  离开以前
    2021-01-11 17:11

    Background

    • In Dart an Exception is for an expected bad state that may happen at runtime. Because these exceptions are expected, you should catch them and handle them appropriately.
    • An Error, on the other hand, is for developers who are using your code. You throw an Error to let them know that they are using your code wrong. As the developer using an API, you shouldn't catch errors. You should let them crash your app. Let the crash be a message to you that you need to go find out what you're doing wrong.
    • An assert is similar to an Error in that it is for reporting bad states that should never happen. The difference is that asserts are only checked in debug mode. They are completely ignored in production mode.

    Read more on the difference between Exception and Error here.

    Next, here are a few examples to see how each is used in the Flutter source code.

    Example of throwing an Exception

    This comes from platform_channel.dart in the Flutter repo:

    @optionalTypeArgs
    Future _invokeMethod(String method, { required bool missingOk, dynamic arguments }) async {
      assert(method != null);
      final ByteData? result = await binaryMessenger.send(
        name,
        codec.encodeMethodCall(MethodCall(method, arguments)),
      );
      if (result == null) {
        if (missingOk) {
          return null;
        }
        throw MissingPluginException('No implementation found for method $method on channel $name');
      }
      return codec.decodeEnvelope(result) as T;
    }
    

    The MissingPluginException here is a planned bad state that might occur. If it happens, users of the platform channel API need to be ready to handle that.

    Example of throwing an Error

    This comes from artifacts.dart in the flutter_tools repo.

    TargetPlatform _currentHostPlatform(Platform platform) {
      if (platform.isMacOS) {
        return TargetPlatform.darwin_x64;
      }
      if (platform.isLinux) {
        return TargetPlatform.linux_x64;
      }
      if (platform.isWindows) {
        return TargetPlatform.windows_x64;
      }
      throw UnimplementedError('Host OS not supported.');
    }
    

    First every possibility is exhausted and then the error is thrown. This should be theoretically impossible. But if it is thrown, then it is either a sign to the API user that you're using it wrong, or a sign to the API maintainer that they need to handle another case.

    Example of using asserts

    This comes from overlay.dart in the Flutter repo:

    OverlayEntry({
      @required this.builder,
      bool opaque = false,
      bool maintainState = false,
    }) : assert(builder != null),
          assert(opaque != null),
          assert(maintainState != null),
          _opaque = opaque,
          _maintainState = maintainState;
    

    The pattern in the Flutter source code is to use asserts liberally in the initializer list in constructors. They are far more common that Errors.

    Summary

    As I read the Flutter source code, use asserts as preliminary checks in the constructor initializer list and throw errors as a last resort check in the body of methods. Of course this isn't a hard and fast rule as far as I can see, but it seems to fit the pattern I've seen so far.

提交回复
热议问题