In imperative programs, it’s normal to see
throw statements or
Exceptions are discouraged in FP. Instead, the return value of a function should
contain information about the possible error. It’s very similar to Rust’s
In FP, the
Either type is used to signal that an operation can potentially
fail. It’s quite similar to
Option<T>. The difference is that the “bad” case
may return an additional payload, unlike
None that doesn’t bear any additional
information on why
None was returned.
Either has two possible variants:
Checking For Errors
Either-based flows follow a track where each function may either
succeed or fail. At the end of the flow, the failure scenario should be checked.
There should be a special type for the “left” (error) scenario. We could have a
Error with all necessary properties (like
string Message) and,
when needed, we could create derived error types. Such error types could contain
predefined error messages for convenience.
It is OK to throw exceptions when something is wrong in the program logic. In such a case, an exception is a clear sign that some code needs to be fixed.
Additionally, throwing exceptions is alright during the initialization. In initialization requires connecting to some message bus and that connection fails, it’s an exceptional situation and the progrm should probably terminate.