Pattern match on exceptions
Is your feature request related to a problem? Please describe. try catch for error control flow can often be better represented as pattern matching.
Describe the solution you'd like I'd love to see a feature that allows matching on expressions that can throw exceptions. I posted a code snippet as a rough idea, so definitely open to ideas on improving it. This feature request is inspired by pattern matching on exceptions from languages like ReScript and OCaml: https://ocaml.org/manual/5.3/patterns.html#sss:exception-match https://rescript-lang.org/docs/manual/v11.0.0/pattern-matching-destructuring#match-on-exceptions
match(new URL(unknownStringValue))
.catch()
.ok((v) => v)
.err(P.when(e => e instanceof SomeError), (e) => e )
.err((e) => e)
.run()
I could also see something like this:
match(new URL(unknownStringValue))
.with(P.exception(P.instanceOf(SomeError)), (error) => /* handle */)
.with(P.exception(P._), (error) => error)
.otherwise((url) => url); // not an exception at this point
match(new URL(unknownStringValue))
.with(P.exception(P.instanceOf(SomeError)), (error) => /* handle */)
.with(P.exception(P._), (error) => error)
.with(P.not(P.exception(P._)), (url) => url)
.exhaustive()
Describe alternatives you've considered The alternative is to handle the try/catch separately or to use a library like neverthrow and match on its Result type.
Additional context N/A