I wish 'try' worked like this:
https://effect.website/ might be worth looking into.
When I first tried Go, this was what I wanted for JS/TS too. So, I created go-try package and still using it for some hobby projects of mine. https://www.npmjs.com/package/go-try Not something huge and there are other similar packages. And of course, having a built-in syntax for this would be so cool.
Been experimenting with some ways to do this in TS, here is a WIP: https://tinyurl.com/3mvhwj54
That's much better! Removing nesting blocks and keep you handle errors in the same place. Why putting `result` before `error`? Seems it can introduce unsafe patterns. If the user really wants to ignore the error he can always do `[, result]` instead.
This looks like Monad from functional programming, if I'm not wrong. Once I learned about it, I started using it wherever feasible. However, some people also like the result pattern instead of the result Monad for simplicity.
In sequence, you need to add an `if` statement, right? Just curious why will better than a `try/catch/finally` statement?
Errors as values okay. What about the pros and cons of that representation. Like why pick `Pair` over something like `Either` in ``` type Pair<E,A> = [result: A, error: E]; type Either<E,A> = { _tag: "left"; left: E } | { _tag: "right"; right: A } ``` `Pair` is a product-type and you could skip or forget to look at the error where as `Either` is a sum-type that forces you to look at the value. The mantra in much of functional programming is to "make illegal states unrepresentablel" hence the sum type would be preferred. Why is it called a sum-type and a product-type? Glad you asked go and read: https://codewords.recurse.com/issues/three/algebra-and-calculus-of-algebraic-data-types Did you know that `Pair` type is the anonymous product-type and `Either` is the anonymous sum-type? Think about it. Does any of this matters? Maybe not but it is interesting :)
pros and cons for most cases I prefer exceptions stack traces
This utility function I wrote has been my solution for awhile. But I also like your tuple style. Maybe I’ll adopt it. 😊 type TryCatchResult<T> = { error?: Error; result?: T; }; export const tryCatch = async <T = unknown>( fn: (...args: unknown[]) => Promise<T>, ...args: unknown[] ): Promise<TryCatchResult<T>> => { let error; let result; try { result = await fn(...args); } catch (caughtError) { error = caughtError as Error; } return {error, result}; };
Software Engineer | Tech Lead at NN Bank
1moI created a utility library to achieve this a while ago, this has made my projects way easier to read and error handling has improved a lot! Here's the lib: https://github.com/sergioflores-j/ts-to-go/tree/main/packages/wrapException