Twitten - type safe & expressive error-handling
Problems solved
- Type-safe error-handling for JS & TS
- Ubiquitous language for error-handling
Introduction
The twitten library lets you handle errors in JavaScript and TypeScript in a type safe and expressive way. The way this is done is nothing new, especially if you're familiar with how success and error cases are handled in the functional world. What's unique as far as I know is that this little library utlize 'Happy & Sad path' temrinology drawn from the world of testing.
Examples
How we usually do when we only have the try/catch + throw jump statement
try catch error
CONS
-
This approach makes our code harder to reason about than it has to be. Since js and ts does not allow us to embedd the throw jump statement in our function and method signatures, we have to rip up the hood and read the implementation details for clues to what errors we could handle.
-
There's more to it than that! Like other jump statements the throw statement makes the control flow of our applications harder to reason about. The control flow following an expected path from module
a -> b -> c...
is disturbed. We could have the control go from modulea -> d...
ora -> b -> c -> g -> p -> x..-
. There are many possibilites, and its hard to reason about! -
Adding to the stack of hard to reasons, js and ts doesn't have the powerful catch clause that we know from languages like C#.
import { Path, Happy, Sad } from "twitten"
The Altenrative - Path with explicit type checking & unwrap
//Must do explicit type checking before we know the correct type of outcome; if Path.isHappyuser.outcome console.loguser.outcome.username, user.outcome.password;else //outcome.message refers to 'Error.message' console.loguser.outcome.message;
Path with continuations
; user.onHappyPathconsole.logusr.username, usr.password .onSadPathconsole.logerror.message;
Path with more continuations
; user.onHappyPath.onHappyPathusr.username.replace" ", "_" .onHappyPathconsole.loguname;
Conclusion
By embedding errors within the type system, we force awarness of potential failures upon consumers of our code. By doing so we make a clear distinction between unexpected and exceptional errors (exceptions) on one side, and expected errors (sad paths) on the other.
If an exception bubbles up to the end-user it will not have anything to with the expected like a input validation error, so we know that something went seriously wrong.