Switch on Specific Errors
Branch by which error was returned.
Not All Errors Are Equal
One fallback rarely fits every failure. A missing file and bad input often need different handling, so you want to branch by which error occurred.
Capture Then switch
Capture the error from catch, then feed it into a switch. Each case can respond to one specific error in its own way.
open(path) catch |err| switch (err) {
error.NotFound => create(path),
else => return err,
};All lessons in this course
- Recover with catch
- Switch on Specific Errors
- errdefer for Failure Cleanup
- Wrapping and Re-throwing Errors