Blog>
Snippets

File System Access Error

Implement a custom FileAccessError class to handle errors that may occur when attempting to read, write, or manipulate files on the server's filesystem.
class FileAccessError extends Error {
  constructor(message, operation, fileName) {
    super(message);
    this.name = 'FileAccessError';
    this.operation = operation;
    this.fileName = fileName;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, FileAccessError);
    }
  }
}
Defines a custom Error class specific to file system access operations. An instance of this class will carry additional information about the operation being performed (e.g., 'read', 'write') and the name of the file involved in the error.
function readFile(fileName) {
  try {
    const data = fs.readFileSync(fileName, 'utf8');
    console.log(`File content: ${data}`);
  } catch (error) {
    throw new FileAccessError('Failed to read the file', 'read', fileName);
  }
}
This function attempts to read a file synchronously. If an error occurs, it throws a FileAccessError with the operation performed and the name of the file.
try {
  readFile('non-existent-file.txt');
} catch (error) {
  if (error instanceof FileAccessError) {
    console.error(`Error during file operation '${error.operation}' on file '${error.fileName}': ${error.message}`);
  } else {
    console.error('An unexpected error occurred:', error);
  }
}
This try-catch block is a usage example where readFile is called and the potential FileAccessError is caught and handled, printing a relevant error message to the console.