Introduction
Hi, I guess! It's been a while since I have posted something in here. Recently I've been dealing a lot with libraries in TypeScript which involve lots of remote dependencies such as database connections or http requests You know how it's annoying to wrap everything in try-catch, especially when you don't even know in advance whether a certain function throws or not! Actually, I really love how Go handles errors:
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
// do something with the open *File f
It returns two values, and you should always check whether the error value is not nil. That's neat and disciplined. In Go, you are always aware of potential errors and you always handle them. Go does not use exceptions at all.
Yet I also love the elegance and flexibility of TypeScript and I started to think how I could achieve something similar (at least remotely) in this language.
Always check
That's how I came to these functions:
async function checkAsync<Args extends any[], Type>(
fnToCheck: (...args: Args) => Promise<Type>,
...args: Args
): Promise<Type | Error> {
try {
const result = await fnToCheck(...args);
return result;
} catch (e) {
return new Error(String(e), { cause: e });
}
}
function check<Args extends any[], Type>(
fnToCheck: (...args: Args) => Type,
...args: Args
): Type | Error {
try {
const result = fnToCheck(...args);
return result;
} catch (e) {
return new Error(String(e), { cause: e });
}
}
It differs from Go approach, but still does the job: instead of try-catch, you just have to check your function, and you get a Type | Error. Then you check for the error, and you are good to go! Essentially it's just a try-catch wrapper which doesn't throw but instead returns errors as values. Of course, it doesn't know whether some functions throw or not (apart from the functions defined by you), but this is still an improvement.
I have published this as an npm package, it works with all runtimes and it's type-safe.
Here is the repo link: https://github.com/zakharsmirnoff/always-check
Here is the npm link: https://www.npmjs.com/package/always-check
Feel free to discuss in the comments, maybe I'm missing something or maybe there is some functionality you might want to add?
Top comments (0)