I’m trying to handle exceptions thrown by NodeJS using TypeScript.
For example, if I get an ECONNREFUSED
exception, it’s of type SystemError
.
But as of now, because err
is of type any
, I can only do this
redisClient.on('error', (err) => {
console.log('Error: ', err);
});
But I would like to narrow down the error type, similar to this:
redisClient.on('error', (err) => {
if (err instanceof ErrnoException) {
if(err.code === 'ECONNREFUSED ') {
throw new Error('Connection refused');
}
}
throw err;
});
But unfortunately, SystemError
is not exported in Node.
I did find a discussion on GitHub from 4 years ago regarding NodeJS.ErrnoException
, but seems like it was removed.
Is it currently possible in NodeJS?
2
Answers
Here’s how you can handle such errors in TypeScript:
Explanation:
The function isErrnoException is a custom type guard that checks whether the err object has the properties typically found on a NodeJS.ErrnoException (like code, errno, and syscall).
This function is used to narrow down the type from unknown to NodeJS.ErrnoException.
Inside the error event handler, we first check if the error is an ErrnoException using the type guard.
If it is, we further inspect the code property to handle specific system errors like ECONNREFUSED.
Pls try this to handle errors in Typescript:
we can also use instanceof