cross-org / jwt

A versatile JSON Web Token (JWT) library with cross-runtime compatibility
MIT License
4 stars 0 forks source link

Return errors instead of throwing them #3

Open Peruibeloko opened 2 weeks ago

Peruibeloko commented 2 weeks ago

Motivations:

Pinta365 commented 2 weeks ago

Hi @Peruibeloko,

Thanks for raising this point about error handling!

While I appreciate your perspective on exceptions as an anti-pattern, I see them as a valid tool in many scenarios, especially for handling truly exceptional situations (like runtime errors).

That said, I acknowledge that returning errors can improve code clarity in certain cases. I'm not planning on making a wholesale change to the error handling right now, but I'm definitely open to exploring a hybrid approach in the future. This might involve returning errors for more predictable scenarios and reserving exceptions for truly unexpected issues.

Would you be willing to share some specific examples from your experience where you've found returning errors to be a particularly effective approach? This would help me understand your use case better.

Peruibeloko commented 1 week ago

Absolutely @Pinta365! Thanks for the attention :)

My current use case is perhaps one of the most common: Issuing and verifying JWTs for Bearer Authentication. The suggestion stems from my current setup which relies on using the aud field for storing the user email.

Since the signing keys are unique to each user (a possibly unfortunate design choice), I need to first verify the integrity of the JWT, before retrieving the user email from the aud field.

Unsafely parsing the JWT to check for its integrity may be avoided in my specific case, but its nonetheless a pretty common thing to do (I suppose :P) in order to quickly reject any invalid requests, before attempting to fully verify the message, which might pose workload implications.

All this really boils down to preference, as you said yourself, and could easily be circumvented by wrapping the exception handling inside an unthrow function, which either returns the result of a successful invokation, or the error itself (which can be type checked using generics). I've been able to implement such workaround, and it works quite well! But I'd like to propose the discussion either way :) (Reference)

I'm also open to help implementing said 'mixed' approach, which reminds me of Carson Gross' take on APIs

EDIT: I also just remembered that TypeScript currently does not infer exceptions types, which even though is listed on my original topic list, is an important point to make, as it requires both maintainers to explicitly declare all possible thrown exceptions on the JSDoc, and developers to explicitly import and use them in their own code, which can lead to worse code quality overall.