Skip to main content
StatusFlow provides a set of HTTP exception classes that extend the base HttpException class. These exceptions are designed to be thrown in your application code and handled by Express error middleware.

HttpException Base Class

The base class that all HTTP exceptions extend from.

Class Definition

class HttpException extends Error {
  public readonly status: number;
  public readonly details?: unknown;
  
  constructor(status: number, message: string, details?: unknown)
}

Constructor Parameters

status
number
required
The HTTP status code for this exception.
message
string
required
The error message describing what went wrong.
details
unknown
Optional additional details about the error. Can be any type (object, array, string, etc.).

Properties

status
number
The HTTP status code associated with this exception. This is a readonly property.
details
unknown
Additional details about the error, if provided. This is a readonly property.
message
string
The error message (inherited from Error).
stack
string
The stack trace (inherited from Error). Automatically captured if available.

Example

import { HttpException } from 'status-flow';

throw new HttpException(418, "I'm a teapot", { 
  reason: 'Coffee brewing not supported' 
});

Exception Classes

StatusFlow provides pre-built exception classes for common HTTP error scenarios.

BadRequestException

Thrown when the request is malformed or invalid.
class BadRequestException extends HttpException
message
string
default:"'Bad Request'"
The error message.
details
unknown
Optional additional error details.
Status Code: 400 Example:
import { BadRequestException } from 'status-flow';

// Basic usage
throw new BadRequestException();

// With custom message
throw new BadRequestException('Invalid email format');

// With details
throw new BadRequestException('Validation failed', {
  errors: [
    { field: 'email', message: 'Must be a valid email' },
    { field: 'age', message: 'Must be at least 18' }
  ]
});

UnauthorizedException

Thrown when authentication is required but not provided or invalid.
class UnauthorizedException extends HttpException
message
string
default:"'Unauthorized'"
The error message.
details
unknown
Optional additional error details.
Status Code: 401 Example:
import { UnauthorizedException } from 'status-flow';

// Basic usage
throw new UnauthorizedException();

// With custom message
throw new UnauthorizedException('Invalid credentials');

// With details
throw new UnauthorizedException('Token expired', {
  expiredAt: '2026-03-07T12:00:00Z',
  tokenType: 'Bearer'
});

ForbiddenException

Thrown when the user is authenticated but doesn’t have permission to access the resource.
class ForbiddenException extends HttpException
message
string
default:"'Forbidden'"
The error message.
details
unknown
Optional additional error details.
Status Code: 403 Example:
import { ForbiddenException } from 'status-flow';

// Basic usage
throw new ForbiddenException();

// With custom message
throw new ForbiddenException('Insufficient permissions');

// With details
throw new ForbiddenException('Admin access required', {
  requiredRole: 'admin',
  userRole: 'user'
});

NotFoundException

Thrown when the requested resource cannot be found.
class NotFoundException extends HttpException
message
string
default:"'Not Found'"
The error message.
details
unknown
Optional additional error details.
Status Code: 404 Example:
import { NotFoundException } from 'status-flow';

// Basic usage
throw new NotFoundException();

// With custom message
throw new NotFoundException('User not found');

// With details
throw new NotFoundException('Resource not found', {
  resourceType: 'User',
  resourceId: '12345'
});

ConflictException

Thrown when the request conflicts with the current state of the server.
class ConflictException extends HttpException
message
string
default:"'Conflict'"
The error message.
details
unknown
Optional additional error details.
Status Code: 409 Example:
import { ConflictException } from 'status-flow';

// Basic usage
throw new ConflictException();

// With custom message
throw new ConflictException('Email already exists');

// With details
throw new ConflictException('Duplicate entry', {
  field: 'email',
  value: '[email protected]',
  existingId: '67890'
});

InternalServerErrorException

Thrown when an unexpected error occurs on the server.
class InternalServerErrorException extends HttpException
message
string
default:"'Internal Server Error'"
The error message.
details
unknown
Optional additional error details.
Status Code: 500 Example:
import { InternalServerErrorException } from 'status-flow';

// Basic usage
throw new InternalServerErrorException();

// With custom message
throw new InternalServerErrorException('Database connection failed');

// With details
throw new InternalServerErrorException('Unexpected error', {
  originalError: error.message,
  stackTrace: error.stack
});

Complete Usage Example

In a Service Layer

import { 
  NotFoundException, 
  BadRequestException,
  ConflictException 
} from 'status-flow';

class UserService {
  async createUser(email: string, password: string) {
    // Validation
    if (!email || !password) {
      throw new BadRequestException('Email and password are required');
    }
    
    // Check for duplicates
    const existing = await this.findByEmail(email);
    if (existing) {
      throw new ConflictException('User with this email already exists', {
        email
      });
    }
    
    // Create user
    return await database.users.create({ email, password });
  }
  
  async getUser(id: string) {
    const user = await database.users.findById(id);
    
    if (!user) {
      throw new NotFoundException('User not found', { userId: id });
    }
    
    return user;
  }
}

With Express Error Middleware

import express from 'express';
import { httpErrorMiddleware, NotFoundException } from 'status-flow';

const app = express();

app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await userService.getUser(req.params.id);
    res.json({ success: true, data: user });
  } catch (error) {
    next(error); // Pass to error middleware
  }
});

// Error middleware handles HttpException instances
app.use(httpErrorMiddleware);

With Try-Catch

import { HttpException, BadRequestException } from 'status-flow';

try {
  validateInput(data);
} catch (error) {
  if (error instanceof HttpException) {
    console.log(`HTTP ${error.status}: ${error.message}`);
    console.log('Details:', error.details);
  } else {
    // Handle non-HTTP exceptions
    console.error('Unexpected error:', error);
  }
}

Type Checking

You can check if an error is an HttpException:
import { HttpException } from 'status-flow';

function handleError(error: unknown) {
  if (error instanceof HttpException) {
    // It's an HTTP exception
    console.log(`Status: ${error.status}`);
    console.log(`Message: ${error.message}`);
    console.log(`Details:`, error.details);
  } else {
    // Handle other error types
    console.error('Unknown error:', error);
  }
}

Build docs developers (and LLMs) love