【问题标题】:What is the correct way to catch both Error and Exception following `effective dart`?在“有效飞镖”之后捕获错误和异常的正确方法是什么?
【发布时间】:2021-02-22 11:59:02
【问题描述】:

此代码示例

import 'package:flutter_test/flutter_test.dart';

void main() {
  const one = 1;
  String oneAsString() => one as String;

  test('Make sure it fails', () {
    var s;
    var _e;
    try {
      s = oneAsString();
    } on Error catch (e) {
      _e = e;
    }
    expect(s == null, true, reason: 'should fail');
    expect(_e == null, false, reason: 'error or exception should be returned');
  });

  test('Catchin Error', () {
    var _e;
    try {
      oneAsString();
    } on Error catch (e) {
      _e = e;
    }
    expect(_e is Error, true, reason: 'should be an error');
  });

  test('Catchin Exception', () {
    var _e;
    try {
      oneAsString();
    } on Exception catch (e) {
      _e = e;
    }

    expect(_e is Exception, true, reason: 'should be an exception');
  });

  test('Why not BOTH', () {
    var _e;
    try {
      oneAsString();
    } on Error catch (e) {
      _e = e;
    } on Exception catch (e) {
      _e = e;
    }

    expect(_e is Error, true, reason: 'should be an error');
    expect(_e is Exception, false, reason: 'should NOT be an exception');
  });
}

输出这个结果

00:02 +2 -1: Catchin Exception [E]                                                                                                                                                                          
  type 'int' is not a subtype of type 'String' in type cast
  test/widget_test.dart 5:31   main.oneAsString
  test/widget_test.dart 31:18  main.<fn>
  
00:02 +3 -1: Some tests failed.   

最安全的方法似乎是Why not BOTH,但遵循effective dart
(使用包 effective_dart 强制执行)
分析抱怨avoid_catching_errors

不要显式捕获错误或实现它的类型。

错误与异常的不同之处在于可以分析和分析错误 在运行前阻止。几乎从不需要 在运行时捕获错误。

不好:

尝试 { somethingRisky(); } on Error catch(e) { doSomething(e); } 好:

尝试 { somethingRisky(); } 关于异常 catch(e) { doSomething(e); }

如果我简单的话

try {} catch (e) {}

分析器抱怨avoid_catches_without_on_clauses

避免没有 on 子句的捕获。

使用不带 on 子句的 catch 子句会使您的代码容易 遇到不会抛出的意外错误(因此会发生 没有注意到)。

不好:

try { somethingRisky() } catch(e) { doSomething(e);好:

try { somethingRisky() } on Exception catch(e) { doSomething(e); }

捕获ErrorException 的正确方法是什么?

【问题讨论】:

    标签: flutter dart exception error-handling dart-analyzer


    【解决方案1】:

    @Miyoyo 的答案重新发布到r/FlutterDev discord

    Optimally? You do not catch error
    Just, at all
    Remember effective dart is Guidelines
    Using them as gospel will make some things impossible
    Catching error is deliberately made to be "not according to guidelines"
    

    因为你不应该这样做

    对于我的用例,我将添加

    // ignore_for_file: avoid_catching_errors

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 2020-11-29
      • 2019-09-28
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多