I develop in Typescript and I'm often reading how I should handle errors with Either<Left,Right> instead of throwing exceptions. I've read about this so many times and I just can't fathom why I would ever want to do this. I assume I'm missing something so I thought I would ask here.
I'll briefly describe how I use exceptions in my web app. I wrap every API endpoint in a try/catch block. Further up the call stack I throw objects which are either ExpectedError or UnexpectedError. In my catch block I return an invalid HTTP response and an error message. If the error is expected then the user sees a relevant message, if it's unexpected then the error appears more generic to the user and gets logged in Sentry for review.
What exactly is missing from using this approach? Whenever I read into Either<Left,Right> it just seems like I would be introducing way more code into my project with no clear benefit. I understand that when the error is not something that should fail the user request then explicit handling is required, but that seems to be way less common and I can still do that? In most scenarios I want to end whatever the user is attempting and communicate to them why there was failure, exceptions seem far more efficient for that..
TS function types don’t include expected exceptions. Unlike Java which has Exceptions in its method signatures (unless it’s a Runtime), you cannot know what Error might be thrown. It’s on the developer to write try/catch and the compiler can’t enforce it. The TS compile can enforce a Result or Either type.
Pattern matching is in vogue right now. Statement based try/catch it out of style compared to Enum pattern matching, since try/catch doesn’t evaluate to a value but pattern matching does. You can pattern match on Either.
There was a long standing bug with V8 that caused code with try/catch to not be optimized. This caused many JS developers to avoid throwing exceptions. I think it’s been addressed, but people now avoid exceptions as dogma.