DEV Community

Discussion on: Type-Safe Error Handling In TypeScript

 
_gdelgado profile image
Gio • Edited

But what if one of your colleagues added a new feature that uses a new third-party library and forgot to wrap it inside of a try/catch statement?

Yeah this definitely can occur. However, code review should prevent this sort of situation from happening too often. And it's ok. People make mistakes, no one's perfect. The team can retractively wrap the unsafe code in a try catch as part of their post-mortem.

This module isn't about creating the perfect codebase. Nor am I saying that you should never throw exceptions (how ironic). Strict adherence to dogma is never good!

What I am trying to say is this:

  • using throw as a control flow mechanism is suboptimal
  • modelling the various states of your functions (including whether your function could fail or not) within the type system leads to self-documenting code that is more obvious to others and easier to maintain

Wouldn't it lead to a more serious problem because inside your core codebase(like in your business rules) you don't have any ...

Hmm this depends at what depth the error is coming from and whether something higher up on the call stack does have a try / catch. The team needs to collectively agree to this sort of approach (hello coding guidelines!). This is more of a cultural / non-technical problem around enforcing a certain thing in your codebase.

Also, having a "catch all" try catch statement isn't really going to help you much. If you don't know what you're catching then you can't do much with it. So the counterargument in favor of having one catch statement at the top of your program is kind of irrelevant. All you can do is log the error? And maybe return a 500 to your users?