OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:async'; |
| 6 |
| 7 /// [Try] is similar to Haskell monad, where |
| 8 /// a computation may throw an exception. |
| 9 /// There is no checking of passing null into |
| 10 /// the value, so be mindful. |
| 11 class Try<T> { |
| 12 final T _val; |
| 13 final StackTrace _stackTrace; |
| 14 final Exception _err; |
| 15 |
| 16 Try.from(this._val) |
| 17 : _err = null, |
| 18 _stackTrace = null; |
| 19 |
| 20 Try.fail(this._err, this._stackTrace) : _val = null; |
| 21 |
| 22 Try<S> bind<S>(S f(T)) { |
| 23 if (_err != null) { |
| 24 return new Try.fail(_err, _stackTrace); |
| 25 } |
| 26 try { |
| 27 return new Try<S>.from(f(_val)); |
| 28 } catch (ex, stackTrace) { |
| 29 return new Try<S>.fail(ex, stackTrace); |
| 30 } |
| 31 } |
| 32 |
| 33 Future<Try<S>> bindAsync<S>(Future<S> f(T)) async { |
| 34 if (_err != null) { |
| 35 return new Try.fail(_err, _stackTrace); |
| 36 } |
| 37 try { |
| 38 return new Try.from(await f(_val)); |
| 39 } catch (ex, stackTrace) { |
| 40 return new Try.fail(ex, stackTrace); |
| 41 } |
| 42 } |
| 43 |
| 44 void fold(caseErr(Exception ex, StackTrace st), caseVal(T)) { |
| 45 if (_err != null) { |
| 46 caseErr(_err, _stackTrace); |
| 47 } else { |
| 48 caseVal(_val); |
| 49 } |
| 50 } |
| 51 |
| 52 bool get isError => _err != null; |
| 53 |
| 54 Exception get error => _err; |
| 55 StackTrace get stackTrace => _stackTrace; |
| 56 |
| 57 T get value => _val; |
| 58 |
| 59 T getOrDefault(T defval) => _err != null ? defval : _val; |
| 60 } |
| 61 |
| 62 Try<T> tryStart<T>(T action()) { |
| 63 return new Try<int>.from(0).bind<T>((dummy) => action()); |
| 64 } |
| 65 |
| 66 Future<Try<T>> tryStartAsync<T>(Future<T> action()) { |
| 67 return new Try<int>.from(0).bindAsync<T>((dummy) => action()); |
| 68 } |
OLD | NEW |