Handling your logic with composable functions makes your code declarative, leading to code that's easy to read and easy to test. Breaking that up to wrap some risky function in a
try/catch block introduces imperative code and makes it harder to maintain that declarative approach. With Ramda's
tryCatch function, you can handle errors right in the middle of a composition and leave your code clean and functional. We'll also see how you can use
propOr to avoid common "cannot find X of undefined" errors.
Maybe due to an evolution of the library (I'm using "ramda": "^0.25.0")
prop function doesn't raise error when provided
undefined or an object with an undefined targeted property, so the
tryCatch won't catch anything. And the error will occur on
Here is a working example:
const getName = R.prop("name") const getUpperName = R.pipe( getName, R.tryCatch(R.toUpper, R.always("DEFAULT")), )
@Sébastien: good point, and I believ that this error throwing was a bug.
propOr should now work like
pathOr and respond with an
undefined instead of a new error when given bad data.