Blog>
Snippets

Custom Async Error Handling

Illustrate the creation of an AsynchronousOperationError class to encapsulate errors that specifically arise during asynchronous operations.
class AsynchronousOperationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AsynchronousOperationError';
  }
}
Define a custom error class to specifically represent errors during asynchronous operations.
async function performAsyncOperation() {
  try {
    // Simulate an async operation that could fail
    const result = await someAsynchronousTask();
    return result;
  } catch (error) {
    // Wrap the error into AsynchronousOperationError
    throw new AsynchronousOperationError('An error occurred during the async operation');
  }
}
Asynchronous function where the error is caught and wrapped in the custom AsynchronousOperationError.
function someAsynchronousTask() {
  return new Promise((resolve, reject) => {
    // Simulating asynchronous task with a timer
    setTimeout(() => {
      const success = Math.random() > 0.5;
      if (success) {
        resolve('Operation succeeded');
      } else {
        reject('Operation failed');
      }
    }, 1000);
  });
}
Simulates an asynchronous task that might succeed or fail randomly, mocking the behavior of an actual asynchronous operation.
async function initiateAsyncOperation() {
  try {
    const operationResult = await performAsyncOperation();
    console.log('Async operation result:', operationResult);
  } catch (error) {
    if (error instanceof AsynchronousOperationError) {
      console.error('Custom async operation error:', error.message);
    } else {
      console.error('Unexpected error:', error);
    }
  }
}
Function to initiate the asynchronous operation, handle errors using the custom AsynchronousOperationError class, and log the outcome.