Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Why should I use Either<Left,Right> over exceptions?
2 points by solumunus on May 25, 2023 | hide | past | favorite | 2 comments
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..



I don’t agree with using Either or Result types in JavaScript, but I can see some arguments.

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.


Exception handling makes it hard to do functional composition. So using a Result /Maybe type enables the functions to be placed together easier. If you don't care about functional composition then I don't think it really matters.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: