[Typescript] Toolbox: isError
function isError(err: any): err is Error {
return err instanceof Error;
}
try {
somethingRisky()
} catch(err: unknown) {
if (isError(err)) {
console.log(err.stack)
} else {
console.log(err)
}
}
You can also have the following in test case, but do NOT put into production:
function assertIsError(err: any): asserts err is Error {
if(!(err instanceof Error)) throw new Error(`Not an error: ${err}`);
}
try {
somethingRisky();
} catch(err: unknown) {
// in a test case, you expect `err` must be an Error type
// if not, throw Error
assertIsError(err);
console.log(err.stack)
}