w3resource

TypeScript File Handling with error propagation

TypeScript Error Handling : Exercise-9 with Solution

Write a TypeScript program that reads data from a file using Node.js. Implement error propagation by handling errors at different levels of your code (e.g., in a function, in middleware, and in the main application).

Sample Solution:

TypeScript Code:

import * as fs from 'fs';

// Custom error class for file-related errors
class FileError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'FileError';
  }
}

// Function to read data from a file and propagate errors
function readDataFromFile(filename: string): Promise {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (error, data) => {
      if (error) {
        reject(new FileError(`Error reading file: ${error.message}`));
      } else {
        resolve(data);
      }
    });
  });
}

// Middleware function to handle file-related errors
function middlewareErrorHandling(): void {
  const filename = 'test.txt'; // Change the filename to test different scenarios

  readDataFromFile(filename)
    .then((data) => {
      console.log(`Data from file: ${data}`);
    })
    .catch((error) => {
      console.error(`Middleware Error: ${error.message}`);
      throw error; // Re-throw the error to propagate it to the main application
    });
}

// Main application
function mainApplication(): void {
  try {
    middlewareErrorHandling();
    console.log('Application completed.');
  } catch (error) {
    if (error instanceof FileError) {
      console.error(`Main Application Error: ${error.message}`);
    } else {
      console.error(`Main Application Unexpected Error: ${error.message}`);
    }
  }
}

// Execute the main application
mainApplication();

Explanations:

In the exercise above -

  • First, define a custom error class called "FileError" for file-related errors.
  • The "readDataFromFile()" function reads data from a file using the fs module and returns a Promise. It rejects the Promise with a FileError when an error occurs during file reading.
  • We have a middleware function "middlewareErrorHandling()" that calls "readDataFromFile()" function and handles file-related errors at the middleware level. It logs the error and re-throws it to propagate it to the main application.
  • Finally, the main application "mainApplication()" calls the middleware function and handles errors at the application level. It catches and logs both custom FileError and unexpected errors.

Output:

Application completed.
Middleware Error: Error reading file: ENOENT: no such file or directory, open 'G:\ts\test.txt'

Go to:


PREV : TypeScript input validation with custom class.
NEXT : TypeScript sequential API requests with error handling.

TypeScript Editor:

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


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.