Try, catch, but don't throw | Utku's Blog

submited by
Style Pass
2024-09-23 15:30:37

The standard try-catch-throw approach to error handling in TypeScript is not type-safe, making it difficult to explicitly handle different kinds of errors in business logic. This might be okay in small projects where it’s affordable to treat all errors similarly, but it’s not ideal for larger and more complex projects where it’s oftentimes desirable to differentiate between recoverable and unrecoverable errors.

Since the caught error is of type unknown in the catch block, we cannot rely on TypeScript in ensuring that all the possible error types are covered. Suppose that we have a function that can fail due to several reasons such as:

Some of these errors might be recoverable. Such errors should not bubble up to higher abstraction layers lest they disrupt the entire operation. Instead, they should be gracefully handled by the business logic.

For the sake of the argument, let’s assume that we want our system to recover from DecodeError and ValidationError in the example below:

Leave a Comment