skip to Main Content

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


  1. Here’s how you can handle such errors in TypeScript:

      import { RedisClient } from 'redis';
    
    const redisClient = new RedisClient({});
    
    redisClient.on('error', (err: unknown) => {
      if (isErrnoException(err)) {
        if (err.code === 'ECONNREFUSED') {
          throw new Error('Connection refused');
        }
      }
    
      throw err;
    });
    
    function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
      return (
        error instanceof Error &&
        typeof (error as NodeJS.ErrnoException).code === 'string' &&
        typeof (error as NodeJS.ErrnoException).errno === 'number' &&
        typeof (error as NodeJS.ErrnoException).syscall === 'string'
      );
    }
    

    Explanation:

    • Type Guard (isErrnoException):

    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.

    • Error Handling:

    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.

    Login or Signup to reply.
  2. Pls try this to handle errors in Typescript:

    interface NodeSystemError extends Error {
      code?: string;
      errno?: number;
      syscall?: string;
      path?: string;
      address?: string;
      port?: number;
    }
    
    redisClient.on('error', (err) => {
      const error = err as NodeSystemError;
    
      if (error.code === 'ECONNREFUSED') {
        console.error('Connection refused:', error);
        throw new Error('Redis connection refused');
      } else if (error.code === 'EHOSTUNREACH') {
        console.error('Host unreachable:', error);
        throw new Error('Redis host unreachable');
      } else {
        console.error('Unhandled error:', error);
        throw error;
      }
    });

    we can also use instanceof

    redisClient.on('error', (err) => {
      if (err instanceof Error && (err as any).code === 'ECONNREFUSED') {
        console.error('Connection refused:', err);
        throw new Error('Redis connection refused');
      } else if (err instanceof Error && (err as any).code === 'EHOSTUNREACH') {
        console.error('Host unreachable:', err);
        throw new Error('Redis host unreachable');
      } else {
        console.error('Unhandled error:', err);
        throw err;
      }
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search