Skip to content

Instantly share code, notes, and snippets.

@iota9star
Last active October 30, 2022 10:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iota9star/dd88a3fbc8babfe16749bd5918cebe70 to your computer and use it in GitHub Desktop.
Save iota9star/dd88a3fbc8babfe16749bd5918cebe70 to your computer and use it in GitHub Desktop.
No try catch, safe use await in one line.
import 'dart:async';
Future<void> main() async {
final a = await err().noc();
print(a);
print(a.runtimeType);
print(a.hasErr);
print(a.value);
print(a.value.runtimeType);
print(a.error);
print('==============================');
final b = await succ().noc();
print(b);
print(b.runtimeType);
print(b.hasErr);
print(b.value);
print(b.value.runtimeType);
print(b.error);
print('==============================');
final c = await voidf().noc();
print(c);
print(c.runtimeType);
print(c.hasErr);
// safe type check. void not any called.
// print(c.ok);
// print(c.ok.runtimeType);
print(c.error);
}
Future<String?> err() async {
throw UnsupportedError('Unknown error');
}
Future<String> succ() async {
return 'success';
}
Future<void> voidf() async {
print('void function.');
}
extension NeverCatchExtension<T> on Future<T> {
Future<NeverCatch<T>> noc() => noCatch(this);
}
Future<NeverCatch<T>> noCatch<T>(Future<T> future) {
return future.then<NeverCatch<T>>((T value) {
return NeverCatch.val(value);
}).catchError((error, stackTrace) {
return NeverCatch.cat<T>(error, stackTrace);
});
}
class NeverCatch<T> {
NeverCatch._({this.value, this.error, this.stackTrace});
static NeverCatch<T> val<T>(T value) {
return NeverCatch._(value: value);
}
static NeverCatch<T> cat<T>(Object? error, [StackTrace? stackTrace]) {
return NeverCatch._(error: error, stackTrace: stackTrace);
}
final T? value;
final Object? error;
final StackTrace? stackTrace;
bool get hasErr => error != null;
@override
String toString() {
return 'NeverCatch(value: $value, error: $error, stackTrace: $stackTrace)';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment