
Security News
Axios Maintainer Confirms Social Engineering Attack Behind npm Compromise
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.
@ingeze/api-error
Advanced tools
A TypeScript library for handling HTTP errors in Express, NestJS, and Fastify APIs.
A comprehensive TypeScript library for consistent HTTP error handling across Express, NestJS, and Fastify APIs. Built with developer experience in mind, providing type-safe error classes and framework-specific middleware for seamless API error management.
npm install @ingeze/api-error
yarn add @ingeze/api-error
pnpm add @ingeze/api-error
This package uses subpath exports to expose integrations for different frameworks (Express, Nest, Fastify, etc.).
import { expressErrorMiddleware } from '@ingeze/api-error/express'
// or
import { NestErrorFilter, NestGenericErrorFilter } from '@ingeze/api-error/nest'
// or
import { fastifyErrorMiddleware } from '@ingeze/api-error/fastify'
This lets you import only what you need, without loading unnecessary code.
To make TypeScript properly recognize subpath exports (like @ingeze/api-error/express), you must use a modern module resolution strategy.
Make sure your tsconfig.json includes:
{
"compilerOptions": {
"moduleResolution": "node16", // or "nodenext" if using ESM
"module": "esnext", // or "commonjs" if using require
"target": "es2020",
"esModuleInterop": true
}
}
Starting from TypeScript 4.7+, node16 and nodenext support the exports field in package.json.
import { BadRequestError, NotFoundError } from '@ingeze/api-error'
// Simple error throwing
throw new BadRequestError()
// With custom details
throw new NotFoundError({
resource: 'user',
id: '12345'
})
// Response format:
{
"success": false,
"type": "NOT_FOUND_USER",
"statusCode": 404,
"message": "User not found",
"details": {
"resource": "user",
"id": "12345"
}
}
import express from 'express'
import { expressErrorMiddleware } from '@ingeze/api-error/express'
import { UserNotFoundError } from '@ingeze/api-error'
const app = express()
// Your routes
app.get('/users/:id', async (req, res) => {
const user = await findUser(req.params.id)
if (!user) {
throw new UserNotFoundError({ userId: req.params.id })
}
res.json(user)
})
// Error handling middleware (must be last)
app.use(expressErrorMiddleware)
import { Module } from '@nestjs/common'
import { APP_FILTER } from '@nestjs/core'
import { NestErrorFilter, NestGenericErrorFilter } from '@ingeze/api-error/nest'
@Module({
providers: [
{
provide: APP_FILTER,
useClass: NestErrorFilter,
},
{
provide: APP_FILTER,
useClass: NestGenericErrorFilter,
},
],
})
export class AppModule {}
import fastify from 'fastify'
import { fastifyErrorMiddleware } from '@ingeze/api-error/fastify'
const app = fastify()
// Set the error handler
app.setErrorHandler(fastifyErrorMiddleware)
import {
BadRequestError,
InvalidUserDataError,
InvalidEmailError,
InvalidProductDataError,
InvalidPostData,
InvalidCommentDataError,
InvalidCategoryDataError,
InvalidFileError,
InvalidImageError,
InvalidAddressError
} from '@ingeze/api-error'
import {
UnauthorizedError,
InvalidTokenError,
InvalidCredentialsError,
AccessTokenError,
RefreshTokenError,
APIKeyError,
UnauthorizedDeviceError
} from '@ingeze/api-error'
import {
ForbiddenError,
ForbiddenUserError,
ForbiddenEmailError,
ForbiddenProductError,
ForbiddenPostError,
ForbiddenCommentError,
ForbiddenCategoryError,
ForbiddenFileError,
ForbiddenImageError,
ForbiddenAddressError
} from '@ingeze/api-error'
import {
NotFoundError,
UserNotFoundError,
EmailNotFoundError,
ProductNotFoundError,
PostNotFoundError,
CommentNotFoundError,
CategoryNotFoundError,
FileNotFoundError,
ImageNotFoundError,
AddressNotFoundError
} from '@ingeze/api-error'
import {
ValidationError,
ValidationUserError,
ValidationEmailError,
ValidationProductError,
ValidationPostError,
ValidationCommentError,
ValidationCategoryError,
ValidationFileError,
ValidationImageError,
ValidationAddressError
} from '@ingeze/api-error'
Create your own error classes with the factory function:
import { createHandleError } from '@ingeze/api-error'
// Define error types
type PaymentErrorType = 'PAYMENT_FAILED' | 'PAYMENT_DECLINED' | 'INSUFFICIENT_FUNDS'
// Create custom error class
const PaymentError = createHandleError<PaymentErrorType>({
name: 'PaymentError',
statusCode: 402,
defaultType: 'PAYMENT_FAILED',
defaultMessage: 'Payment could not be processed'
})
// Usage
throw new PaymentError()
throw new PaymentError('Card declined', 'PAYMENT_DECLINED', {
cardLast4: '4242',
retryAllowed: false
})
import { ErrorHandler } from '@ingeze/api-error'
throw new ErrorHandler(
'Custom error message',
418, // I'm a teapot
'CUSTOM_TYPE',
{ customField: 'value' }
)
All errors follow this consistent structure:
interface ErrorResponse {
success: boolean // Always false
type: string // Error type identifier
statusCode: number // HTTP status code
message: string // Human-readable message
details?: object // Optional additional context
}
import express from 'express'
import { UserNotFoundError, ValidationUserError } from '@ingeze/api-error'
import { expressErrorMiddleware } from '@ingeze/api-error/express'
const app = express()
app.post('/users', async (req, res) => {
const { email, name } = req.body
// Validate required fields
const missing = [];
if (!email) missing.push("Email can't be empty");
if (!name) missing.push("Name can't be empty");
if (missing.length) {
throw new ValidationUserError({ missing: missing.join('. '), missing });
}
// Check if user already exists
const existingUser = await findUserByEmail(email)
if (existingUser) {
throw new ValidationUserError({
field: 'email',
reason: 'already exists'
})
}
// Create and return the new user
const user = await createUser({ email, name })
res.status(201).json(user)
})
// Global error handler
app.use(expressErrorMiddleware)
import { Injectable } from '@nestjs/common'
import { UserNotFoundError, ValidationUserError } from '@ingeze/api-error'
@Injectable()
export class UserService {
async findUser(id: string) {
const user = await this.userRepository.findById(id)
if (!user) {
throw new UserNotFoundError({ userId: id })
}
return user
}
async updateUser(id: string, data: UpdateUserDto) {
if (!data.email && !data.name) {
throw new ValidationUserError({
message: 'At least one field must be provided'
})
}
const user = await this.findUser(id) // Will throw if not found
return this.userRepository.update(id, data)
}
}
The library is thoroughly tested with comprehensive test coverage:
npm test
For a detailed list of changes and version history, please see the Changelog file.
This project follows Semantic Versioning and documents all notable updates in the changelog to help you stay informed about new features, fixes, and improvements.
MIT © ingEze
Contributions are welcome! Please feel free to submit a Pull Request.
Built with ❤️ by the Ingeze
FAQs
A TypeScript library for handling HTTP errors in Express, NestJS, and Fastify APIs.
We found that @ingeze/api-error demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.

Security News
The Axios compromise shows how time-dependent dependency resolution makes exposure harder to detect and contain.