在Dart中扩展Exception类

7 dart

当我尝试扩展Exception类并且无法弄清楚原因时,我一直收到错误.这是我的自定义异常的代码:

class MyException extends Exception {
  String msg;
  MyException(this.msg);
  String toString() => 'FooException: $msg';
}
Run Code Online (Sandbox Code Playgroud)

该错误在构造函数周围解决.它抱怨"生成构造函数'异常([动态消息]) - >异常'预期,但工厂发现".我该如何解决?

Sha*_*uli 15

你几乎是对的.您需要实现 Exception而不是扩展它.这应该工作:

class MyException implements Exception {
  final String msg;
  const MyException(this.msg);
  String toString() => 'FooException: $msg';
}
Run Code Online (Sandbox Code Playgroud)

你不必做msg最终或构造函数const,但你可以.以下是Exception类(来自dart:core库)的实现示例:

class FormatException implements Exception {
  /**
   * A message describing the format error.
   */
  final String message;

  /**
   * Creates a new FormatException with an optional error [message].
   */
  const FormatException([this.message = ""]);

  String toString() => "FormatException: $message";
}
Run Code Online (Sandbox Code Playgroud)


mag*_*nap 5

我想补充另一个答案:不仅仅是一个消息字符串,让type调用code者可以根据异常类型决定要做什么会很有用。例如:

enum NfcErrorType { communication, parse, timeout, mismatch }

class NfcException implements Exception {
  final NfcErrorType type;

  NfcException(this.type);

  @override
  String toString() {
    return 'NfcException: $type';
  }
}

Run Code Online (Sandbox Code Playgroud)

然后你可以像这样抛出:

throw NfcException(NfcErrorType.parse);
Run Code Online (Sandbox Code Playgroud)

调用者可以这样捕获:

try {
  // ...
} on NfcException catch (err) {
  switch(err.type) {
    case NfcErrorType.parse:
      // do something
      break;
    case NfcErrorType.communication:
      // do something different
      break;
    // .... other cases

  }
} catch(err) {
  // handle some other way...
}
Run Code Online (Sandbox Code Playgroud)