Functions throwing exceptions #3655
Replies: 1 comment 1 reply
-
Hey! I'm glad you wrote this because it was also bugging me but for another reason. In v3, we removed all exceptions, argument number checking, interval correctness, etc. In most cases, people get For the most part, it's expected as the input is not static, and nobody wants users to break apps because they entered something wrong. With parse and format functions, I couldn't decide as I still wanted to let developers know that they used the wrong tokens format. In such cases, getting an Another issue with parse is that a string is expected, and there's no invalid string in JS, at least natively. So, I decided to keep the v2 behavior as is, including the invalid date exception. I like the idea of having an error type. It seems easy to implement. This also could be extended to In v4, my plan is to extract all I18n functions and locales into separate packages, i.e., |
Beta Was this translation helpful? Give feedback.
-
Hi! As a functional programming advocate, I really like the
date-fns/fp
module. I can pick just the function that I need, and it works well within my function compositions!However, the fact that the functions throw exceptions is a bummer 😞. We had some code like
format("MM/dd/yy", new Date(date))
. It was working great until our backend provided an ISO date that was malformed, and the entire page crashed becauseformat
throws ifdate
is anInvalid Date
. Of course, the ways to prevent this is to be more defensive in checking the date (eg,isValid
), or to wrap everything in atry
/catch
, but that's not quite aligned with the principles of functional programming.I'm curious how people deal with this? Just resign to using
try
/catch
? Wrap the functions with other ways of handling errors (Result
monad, etc)?I'm also curious if there has been any discussion about having
date-fns
use alternate ways of error handling that doesn'tthrow
and requiretry
/catch
. Other libraries will more gracefully returnInvalid Date
or similar which is less likely to affect other parts of the code (and crash the page, as in our case).Now that
date-fns
uses typescript, functions that would otherwisethrow
could now return errors as a union with the return type. For example,format
might return astring | { type: "error", message: "Invalid Date" }
. The type system would enforce that the consumer handle these runtime errors at compile time. Something like this might be automatable inconvertToFp
to wrap in atry
/catch
and return something else in the case of an error.Any ideas or insight would be greatly appreciated!
Beta Was this translation helpful? Give feedback.
All reactions