Stream errors
- Dart course
- Advanced
- Lesson 16/83
- 5 min
Learn stream errors and onError.
Stream errors
A stream can publish error events alongside normal elements. When an error is emitted the stream normally closes; no further elements arrive.
It is caught via onError in the listener or with try/catch. The .handleError(fn) transformer catches errors and keeps the stream going.
Example: Stream.error('boom').listen(print, onError: (e) => print('error: $e'));. The error goes to onError, print is never called.
try/catch with await for
When consuming a stream with await for, a thrown error is caught by a normal try/catch. The stream closes, the loop ends.
Example: try { await for (var x in Stream.error('boom')) print(x); } catch (e) { print('error: $e'); }. The error is caught, 'error: boom' prints.
This mirrors synchronous error handling; it looks the same in async flow.
Practice Catch a stream error
Make main async. Add a block try { await Stream.error('boom').forEach(print); } catch (e) { print('hata: $e'); }.
Starter code
void main() {
// make async; wrap an error-emitting stream in try/catch
}Sample solution
void main() async {
try {
await Stream.error('boom').forEach(print);
} catch (e) {
print('hata: $e');
}
}Expected output
hata: boom
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when an error is emitted?
- The stream continues
- The error is ignored
- The program crashes
- The stream normally closes Correct answer
Explanation: an emitted error normally closes the stream.
2 Error-handling options
| Term | Meaning |
|---|---|
onError |
Listener parameter |
try/catch |
with await for |
.handleError |
Transformer |
.toList |
Terminal |
3 Error-handler method
var t = s.____((e) => print('error'));
var t = s.handleError((e) => print('error'));
Explanation: handleError transformer catches errors.