我正在嘗試制作一個通用函式來處理例外以減少代碼重復。
功能是這樣的:
Future<T> exceptionHandler<T, E extends Exception>({
required ValueGetter<Future<T>> tryBlock,
}) async {
try {
return await tryBlock();
} catch (e) {
if (e is E) {
rethrow;
}
throw E( // Error: E isn't a function
error: e.toString(),
);
}
}
我創建了自定義例外,其中之一稱為
AuthException.
此功能的用途如下:
而不是這樣做:
Future<bool> signUp({
required covariant UserModel user,
required String password,
}) async {
try {
// try block code goes here
} catch (e) {
if (e is AuthException) {
rethrow;
}
throw AuthException(
error: e.toString(),
);
}
}
我希望能夠做到這一點:
Future<bool> signUp({
required covariant UserModel user,
required String password,
}) async {
return await exceptionHandler<bool, AuthException>(
tryBlock: () async {
// try block goes here
},
);
}
是這樣定義的AuthException:
class AuthException implements Exception {
final String error;
const AuthException({
required this.error,
});
}
問題是我不能E從exceptionHandler函式中拋出,因為E它是一個型別而不是一個物件。有沒有辦法做到這一點?
uj5u.com熱心網友回復:
您不能直接構造泛型型別引數的實體。Dart 不認為建構式和static方法是類介面的一部分,因此限制E extends Exception并不能保證E具有帶命名引數的未命名建構式error。
相反,您可以讓泛型函式接受構造所需型別的回呼:
Future<T> exceptionHandler<T, E extends Exception>({
required ValueGetter<Future<T>> tryBlock,
required E Function({required String error}) makeException,
}) async {
try {
return await tryBlock();
} catch (e) {
if (e is E) {
rethrow;
}
throw makeException(error: e.toString());
}
}
然后用法是:
Future<bool> signUp({
required covariant UserModel user,
required String password,
}) async {
return await exceptionHandler(
tryBlock: () async {
// try block goes here
},
makeException: AuthException.new,
);
}
我還要注意,您的catch塊將捕獲所有內容,包括通常不贊成的Errors,并且它會丟失堆疊跟蹤,這將使故障更難除錯。我會將條款限制為s 并使用:catchExceptionError.throwWithStackTrace
Future<T> exceptionHandler<T, E extends Exception>({
required ValueGetter<Future<T>> tryBlock,
required E Function({required String error}) makeException,
}) async {
try {
return await tryBlock();
} on Exception catch (e, stackTrace) {
if (e is E) {
rethrow;
}
Error.throwWithStackTrace(
makeException(error: e.toString()),
stackTrace,
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510437.html
標籤:镖哎呀仿制药例外错误处理
上一篇:與泛型型別互動
下一篇:如何正確實作泛型結構
