0
0
NodejsHow-ToBeginner · 3 min read

How to Use Try Catch in Node.js for Error Handling

In Node.js, use a try catch block to run code that might throw errors and catch those errors to handle them safely. Place the risky code inside try, and handle any exceptions inside catch to prevent your app from crashing.
📐

Syntax

The try catch statement has two main parts: try and catch. The try block contains code that might throw an error. If an error happens, the catch block runs and receives the error object to handle it.

Optionally, you can add a finally block that runs code after try and catch, no matter what.

javascript
try {
  // Code that may throw an error
} catch (error) {
  // Code to handle the error
} finally {
  // Code that runs always (optional)
}
💻

Example

This example shows how to use try catch to handle an error when parsing invalid JSON. The catch block catches the error and logs a friendly message instead of crashing the program.

javascript
try {
  const jsonString = '{"name": "Alice", "age": 30}'; // Invalid JSON (missing quotes around age key)
  const user = JSON.parse(jsonString);
  console.log(user.name);
} catch (error) {
  console.error('Failed to parse JSON:', error.message);
}
console.log('Program continues running');
Output
Program continues running
⚠️

Common Pitfalls

One common mistake is putting asynchronous code inside try catch without await. Errors in asynchronous callbacks or promises won't be caught by try catch unless you use async/await.

Also, avoid empty catch blocks that silently ignore errors, as this makes debugging hard.

javascript
/* Wrong: try catch won't catch async errors without await */
try {
  setTimeout(() => {
    throw new Error('Async error');
  }, 100);
} catch (error) {
  console.log('Caught error:', error.message);
}

/* Right: use async function with await */
async function run() {
  try {
    await Promise.reject(new Error('Async error'));
  } catch (error) {
    console.log('Caught async error:', error.message);
  }
}
run();
Output
Caught async error: Async error
📊

Quick Reference

  • try: Wrap code that might fail.
  • catch: Handle errors thrown in try.
  • finally: Run code always, after try/catch.
  • Use async/await to catch async errors.
  • Never leave catch blocks empty; always handle or log errors.

Key Takeaways

Use try catch to handle errors and keep your Node.js app running smoothly.
Put code that might throw errors inside try, and handle errors in catch.
For asynchronous code, use async/await with try catch to catch errors properly.
Avoid empty catch blocks to prevent silent failures.
Use finally to run cleanup code regardless of errors.