Blog>
Snippets

Database Connection Error

Forge a custom DBConnectionError error class, allowing for more granular error handling and logging when there are issues connecting to a database.
class DBConnectionError extends Error {
  constructor(message) {
    super(message);
    this.name = 'DBConnectionError';
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, DBConnectionError);
    }
  }
}
This code defines a custom error class named DBConnectionError that extends from the native JavaScript Error object, allowing for instances of this class to be thrown and caught to handle database connection related errors specifically.
function handleDatabaseOperation() {
  try {
    // Code that attempts to connect to the database...
    // If the connection fails, throw an instance of DBConnectionError
    throw new DBConnectionError('Failed to connect to the database');
  } catch (error) {
    if (error instanceof DBConnectionError) {
      console.error('Database connection error:', error.message);
    } else {
      console.error('General error:', error.message);
    }
  }
}
Here we have a function that simulates a database operation. It contains a try-catch block that catches any errors that occur during the database operation. If there is a database connection error, it throws an instance of the custom DBConnectionError. Within the catch block, the error is checked to see if it is an instance of DBConnectionError, and if so, a specific error message is logged, otherwise, it logs a general error message.