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'
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript input validation with custom class.
Next: TypeScript sequential API requests with error handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics