Skip to content

Latest commit

 

History

History
27 lines (20 loc) · 728 Bytes

how_to_catch_errors_in_node_js.md

File metadata and controls

27 lines (20 loc) · 728 Bytes

How to catch errors in Node.js

In Node.js, use try/catch for synchronous code and attach error listeners for asynchronous code.

// Synchronous error handling
try {
  const data = fs.readFileSync('/path/to/file');
  console.log(data);
} catch (error) {
  console.error('Error reading file:', error);
}

// Asynchronous error handling
fs.readFile('/path/to/file', (error, data) => {
  if (error) {
    return console.error('Error reading file:', error);
  }
  console.log(data);
});

Tags: intermediate, JavaScript, Node.js, Error Handling