calmm-js / partial.lenses

Partial lenses is a comprehensive, high-performance optics library for JavaScript
MIT License
915 stars 36 forks source link

Dealing with exceptions? #187

Closed polytypic closed 6 years ago

polytypic commented 6 years ago

A few of the standard isomorphisms, namely L.uri, L.uriComponent, and L.json, may throw when given invalid input. For example:

L.get(L.uriComponent, '%') // ~throws~> URIError: URI malformed

This behaviour is currently not documented (specified) or tested, so I consider it to be open to be changed as a bug fix (rather than as a breaking change). Also, as a general principle, performing an otherwise valid read or write through an optic in this library should not throw on invalid input to support optimistic queries and updates.

There are a couple of options for "reasonable" alternatives to throwing. One would be to catch and swallow exceptions and propagate undefined as the result:

L.get(L.uriComponent, '%') // ~> undefined

This would be arguably plausible due to the partial semantics, but swallowing exceptions by default is nasty. Another option would be to catch the exception and propagate the error as the result:

L.get(L.uriComponent, '%') // ~> [URIError: URI malformed]

By composing with e.g. L.getter it is also possible to swallow the exception explicitly:

L.get(
  [
    L.uriComponent,
    L.getter(x => x instanceof Error ? undefined : x)
  ],
  '%'
) // ~> undefined

I currently find the option of propagating the error as the result preferable and I find it unlikely that a change to propagate the error as the result would affect many users.

See #185

Feedback is welcome!