w3resource

TypeScript Database Error Handling with custom class

TypeScript Error Handling : Exercise-7 with Solution

Write a TypeScript function that performs database operations. Create a custom error class, 'DatabaseError', for handling database-related errors. Use this error class to catch and log database errors.

Sample Solution:

TypeScript Code:

// Custom error class for database errors
class DatabaseError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'DatabaseError';
  }
}

// Simulated database operation function (replace with actual database operation)
function performDatabaseOperation(): Promise {
  return new Promise((resolve, reject) => {
    // Simulate a database error
    setTimeout(() => {
      reject(new DatabaseError('Database connection failed.'));
    }, 1000);
  });
}

// Function to perform database operations and handle errors
async function performDatabaseOperations(): Promise {
  try {
    await performDatabaseOperation();
    console.log('Database operation successful.');
  } catch (error) {
    if (error instanceof DatabaseError) {
      console.error(`Database Error: ${error.message}`);
    } else {
      console.error(`Unexpected Error: ${error.message}`);
    }
  }
}

// Execute the database operations and handle errors
performDatabaseOperations();

Explanations:

In the exercise above -

  • First, we define a custom error class called 'DatabaseError' that extends the built-in Error class. It takes a custom error message as a parameter and sets the error name.
  • The "performDatabaseOperation()" function simulates a database operation using a Promise and rejects it with a 'DatabaseError' containing a custom error message to simulate a database error.
  • The "performDatabaseOperations()" function performs database operations using await and handles errors using a try-catch block. If a 'DatabaseError' is caught, it displays the custom database error message. Otherwise, it handles other unexpected errors.

Output:

Unexpected Error: Database connection failed.

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript API Error Handling with custom class.
Next: TypeScript input validation with custom class.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-error-handling-exercise-7.php