StatusFlow provides flexible error handling for Express applications through HTTP exceptions and the StatusFlow function. This guide covers different patterns, async error handling, and best practices.
import { NotFoundException, BadRequestException } from 'status-flow';app.get('/users/:id', (req, res) => { const { id } = req.params; if (!id) { throw new BadRequestException('User ID is required'); } const user = database.findUser(id); if (!user) { throw new NotFoundException('User not found'); } res.json({ success: true, data: user });});
app.get('/users/:id', async (req, res) => { try { const { id } = req.params; if (!id) { throw new BadRequestException('User ID is required'); } const user = await database.findUser(id); if (!user) { throw new NotFoundException('User not found'); } res.json({ success: true, data: user }); } catch (error) { // Pass to error middleware next(error); }});
Use the express-async-errors package for automatic error handling:
npm install express-async-errors
import 'express-async-errors'; // Import at the top of your fileimport express from 'express';import { statusFlowMiddleware, NotFoundException } from 'status-flow';const app = express();// Now async errors are automatically caughtapp.get('/users/:id', async (req, res) => { const user = await database.findUser(req.params.id); if (!user) { throw new NotFoundException('User not found'); } res.json({ success: true, data: user });});app.use(statusFlowMiddleware);
When using express-async-errors, import it before creating your Express app. This ensures it patches Express properly.
Use throw to trigger error handling, not return. This ensures errors are caught by middleware:
// ✅ Goodif (!user) { throw new NotFoundException('User not found');}// ❌ Badif (!user) { return res.status(404).json({ error: 'User not found' });}
Add context to exceptions
Include relevant details to help with debugging:
throw new NotFoundException('User not found', { userId: id, searchedIn: 'database', timestamp: Date.now(),});
Use specific exception classes
Choose the most appropriate exception class for the error:
// ✅ Good - specific exceptionthrow new ConflictException('Email already exists');// ❌ Bad - generic exceptionthrow new HttpException(409, 'Email already exists');
Handle async errors properly
Always use try-catch, async handlers, or express-async-errors for async routes:
Throw validation errors before performing expensive operations:
app.post('/users', async (req, res) => { // Validate first if (!req.body.email) { throw new BadRequestException('Email is required'); } // Then perform database operations const user = await database.createUser(req.body); res.json(user);});