Error handling - writing my first blog post
I recently was inspired by an excellent 'introduction to error handling' blog post. https://www.sheshbabu.com/posts/rust-error-handling/
Both the errors and module system posts there are excellent and need to be seen by lots of beginners!
The site has a certificate error at the moment though. Author informed.
I will write a sequel post. I hope this outline is a valuable read in itself... Comments or questions gratefully received
Distinguish between error creation, error handling (several places/strategies), error reporting with context and error logging/summary with very little scope..
Error propagation via Result or Option can be likened to a short circuit exception-like path upwards.
Error objects should be able to contain low level originating context even when returning one of several largely unrelated errors.
Perhaps a 'publishing' type, 'bad subject' variant with context describing where and why the error was flagged. Session X, user Y, generated in function Z. Etc.
From first principles to say thiserror crate's generation of boilerplate of source() or anyhow crate's context for underlying error details in addition to the std error trait covered in the post above.
If instead of a single MyCustomError type with a few variants, I want to propagate errors with context from one of several types, say MyPublishError *or* a variant from MySubscribeError defined and generated from different sources/originating modules/error enums.
Some function return values need conversion into something simpler e.g. as an error summary. E.g. doctests returning EXIT_SUCCESS or EXIT_FAILURE + string. Needs to work implicitly with operator? rather than explicitly with match etc.
Discuss error report() as used by thiserror.
Also mention the termination trait used by doctests as a similar mechanism.
Users of an error variant should not require knowledge of any implementation e.g. downcasting.
E.g. this error using a source() method or anyhow context().
How to interoperate/handle unrecoverable errors with panic etc. These don't seem to play nicely with attempting to return a std::Result or anyhow::Result particularly in a release vs debug context.
Discuss how to structure and decouple modules and their API for error definition that avoids any coupling to implementation.
Lots of examples using the incremental diff style.
Posted Apr 1, 2021, 5:51 AM UTC · edited
I found it an interesting read as a beginner. It gives useful pointers as to when and how to use the different techniques.