Skip to main content

Overview

StatusFlow provides seamless integration with Express through middleware and exception classes. This guide walks you through setting up StatusFlow in your Express application for comprehensive error handling.

Installation

First, ensure you have StatusFlow and Express installed:
npm install status-flow express
npm install --save-dev @types/express

Integration Steps

1

Import StatusFlow components

Import the necessary middleware and exception classes from StatusFlow:
import express from 'express';
import {
  statusFlowMiddleware,
  httpErrorMiddleware,
  BadRequestException,
  NotFoundException,
  UnauthorizedException,
} from 'status-flow';
StatusFlow provides two middleware options:
  • statusFlowMiddleware: For bilingual responses with detailed HTTP status information
  • httpErrorMiddleware: For simpler HTTP exception handling
2

Create your Express app

Set up your Express application as usual:
const app = express();

// Parse JSON bodies
app.use(express.json());

// Parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));
3

Define your routes

Create routes that throw StatusFlow exceptions when errors occur:
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  
  if (!userId) {
    throw new BadRequestException('User ID is required');
  }
  
  // Simulate user lookup
  const user = findUser(userId);
  
  if (!user) {
    throw new NotFoundException('User not found', { userId });
  }
  
  res.json({ success: true, data: user });
});
Pass additional context through the details parameter of exceptions. This helps with debugging and logging.
4

Add error handling middleware

Register the StatusFlow middleware after all your routes:
Use statusFlowMiddleware for bilingual responses with comprehensive HTTP status information:
// All routes go here...

// Register StatusFlow middleware (must be after routes)
app.use(statusFlowMiddleware);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
This middleware:
  • Detects language from x-lang header (en or es)
  • Returns detailed HTTP status metadata
  • Includes possible causes and descriptions
  • Supports custom messages via overrideMessage
Error handling middleware must be registered after all your routes. Express processes middleware in order, so placing it too early will prevent it from catching errors from subsequent routes.

Complete Working Example

Here’s a complete Express application with StatusFlow integration:
import express, { Request, Response } from 'express';
import {
  statusFlowMiddleware,
  BadRequestException,
  NotFoundException,
  UnauthorizedException,
  createSuccessResponse,
} from 'status-flow';

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Mock data
const users = [
  { id: '1', name: 'Alice', email: '[email protected]' },
  { id: '2', name: 'Bob', email: '[email protected]' },
];

// Routes
app.get('/users', (req: Request, res: Response) => {
  const response = createSuccessResponse(users, 'Users retrieved successfully');
  res.json(response);
});

app.get('/users/:id', (req: Request, res: Response) => {
  const { id } = req.params;
  
  if (!id) {
    throw new BadRequestException('User ID is required');
  }
  
  const user = users.find(u => u.id === id);
  
  if (!user) {
    throw new NotFoundException('User not found', { requestedId: id });
  }
  
  res.json(createSuccessResponse(user, 'User found'));
});

app.post('/users', (req: Request, res: Response) => {
  const { name, email } = req.body;
  
  if (!name || !email) {
    throw new BadRequestException('Name and email are required', {
      received: { name: !!name, email: !!email },
    });
  }
  
  const newUser = {
    id: String(users.length + 1),
    name,
    email,
  };
  
  users.push(newUser);
  res.status(201).json(createSuccessResponse(newUser, 'User created'));
});

app.delete('/users/:id', (req: Request, res: Response) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader) {
    throw new UnauthorizedException('Authorization header required');
  }
  
  const { id } = req.params;
  const index = users.findIndex(u => u.id === id);
  
  if (index === -1) {
    throw new NotFoundException('User not found');
  }
  
  users.splice(index, 1);
  res.json({ success: true, message: 'User deleted' });
});

// Error handling middleware (must be last)
app.use(statusFlowMiddleware);

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Testing with Different Languages

When using statusFlowMiddleware, you can test language support:
# Spanish response (default)
curl http://localhost:3000/users/999

# English response
curl -H "x-lang: en" http://localhost:3000/users/999
Spanish response:
{
  "code": 404,
  "success": false,
  "message": "No encontrado",
  "info": {
    "name": "No encontrado",
    "category": "Error del cliente",
    "description": "El recurso solicitado no fue encontrado",
    "possibleCauses": [
      "URL incorrecta",
      "Recurso eliminado",
      "Recurso nunca existió"
    ]
  }
}
English response:
{
  "code": 404,
  "success": false,
  "message": "Not Found",
  "info": {
    "name": "Not Found",
    "category": "Client Error",
    "description": "The requested resource was not found",
    "possibleCauses": [
      "Incorrect URL",
      "Resource deleted",
      "Resource never existed"
    ]
  }
}

Best Practices

Middleware Order

Always register error handling middleware last, after all routes. This ensures it catches errors from all endpoints.

Throw, Don't Return

Use throw new Exception() in your routes. Express will automatically catch thrown errors and pass them to your error middleware.

Add Context

Include relevant details in the exception’s details parameter. This helps with debugging and provides useful information to API consumers.

Async Error Handling

For async routes, use try-catch blocks or express-async-errors package. See the Error Handling guide for details.

Next Steps

Error Handling Patterns

Learn different error handling patterns and async error handling

Custom Responses

Customize response messages and add extra fields

TypeScript Usage

Type-safe error handling with TypeScript

API Reference

Explore the middleware API documentation

Build docs developers (and LLMs) love