</>
Skip to content
Node.js lessons (25/44)

Node.js — Error Handling

Try-Catch

try {
    const data = JSON.parse(invalidJson);
} catch (error) {
    console.error('Parse error:', error.message);
}

Error Types

TypeDescription
ErrorBase error class
TypeErrorWrong type
ReferenceErrorUndefined variable
SyntaxErrorInvalid syntax
RangeErrorOut of range

Custom Errors

class ValidationError extends Error {
    constructor(message, field) {
        super(message);
        this.name = 'ValidationError';
        this.field = field;
    }
}

throw new ValidationError('Invalid email', 'email');

Error Handling Patterns

// Callback
function fetchData(callback) {
    fs.readFile('data.json', (err, data) => {
        if (err) return callback(err);
        callback(null, JSON.parse(data));
    });
}

// Promise
function fetchData() {
    return fs.promises.readFile('data.json')
        .then(data => JSON.parse(data));
}

// Async/Await
async function fetchData() {
    try {
        const data = await fs.promises.readFile('data.json');
        return JSON.parse(data);
    } catch (error) {
        console.error('Error:', error.message);
        throw error;
    }
}

Uncaught Exceptions

process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
    process.exit(1);
});

process.on('unhandledRejection', (reason) => {
    console.error('Unhandled Rejection:', reason);
});

Mini Practice

  1. Use try-catch
  2. Create custom error classes
  3. Handle async errors
  4. Add global error handlers

Up Next

Continue with Debugging — debugging Node.js applications.

Related Topics

Frequently Asked Questions about Error Handling

What is Error Handling in Node.js?

Error Handling is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Error Handling?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Error Handling.

Why is Error Handling important in Node.js?

Error Handling is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.