@geekmidas/errors

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.5万

Type-safe HTTP error classes with full TypeScript support, providing structured error handling for REST APIs and HTTP-based applications.

原始使用文档
文档目录27 节
  1. Features
  2. Installation
  3. Quick Start
  4. Basic Usage
  5. With Error Details
  6. Available Error Classes
  7. Client Errors (4xx)
  8. Server Errors (5xx)
  9. Error Factories
  10. Generic Error Factory
  11. Type Guards
  12. Error Wrapping
  13. Error Serialization
  14. Error Cause Chaining
  15. Express Middleware
  16. Hono Middleware
  17. Custom Error Classes
  18. Error Context
  19. HTTP Status Codes
  20. Best Practices
  21. 1. Use Specific Error Classes
  22. 2. Include Helpful Details
  23. 3. Use Type Guards
  24. 4. Chain Errors
  25. TypeScript Types
  26. Related Packages
  27. License

@geekmidas/errors

Type-safe HTTP error classes with full TypeScript support, providing structured error handling for REST APIs and HTTP-based applications.

Features

  • Type-Safe Errors: Full TypeScript support with proper error hierarchies
  • HTTP Status Codes: Pre-built error classes for all common HTTP errors
  • Structured Error Details: Include additional context and debugging information
  • Error Factories: Convenient factory functions for creating errors
  • Type Guards: Runtime type checking for error instances
  • JSON Serialization: Built-in support for error serialization
  • Error Wrapping: Wrap unknown errors into HTTP errors
  • Cause Chaining: ES2022 error cause support for error chains

Installation

pnpm add @geekmidas/errors

Quick Start

Basic Usage

import {
  BadRequestError,
  NotFoundError,
  UnauthorizedError,
  InternalServerError
} from '@geekmidas/errors';

// Throw specific error types
throw new NotFoundError('User not found');
throw new BadRequestError('Invalid email format');
throw new UnauthorizedError('Invalid token');
throw new InternalServerError('Database connection failed');

With Error Details

import { BadRequestError, NotFoundError } from '@geekmidas/errors';

// Include additional context
throw new NotFoundError('User not found', { userId: '123' });

throw new BadRequestError('Validation failed', {
  field: 'email',
  value: 'invalid-email',
  message: 'Must be a valid email address'
});

Available Error Classes

Client Errors (4xx)

import {
  BadRequestError,           // 400
  UnauthorizedError,        // 401
  ForbiddenError,           // 403
  NotFoundError,            // 404
  MethodNotAllowedError,    // 405
  ConflictError,            // 409
  UnprocessableEntityError, // 422
  TooManyRequestsError      // 429
} from '@geekmidas/errors';

// 400 Bad Request
throw new BadRequestError('Invalid input');

// 401 Unauthorized
throw new UnauthorizedError('Authentication required');

// 403 Forbidden
throw new ForbiddenError('Insufficient permissions', {
  required: 'admin',
  current: 'user'
});

// 404 Not Found
throw new NotFoundError('Resource not found');

// 405 Method Not Allowed
throw new MethodNotAllowedError('DELETE not supported', ['GET', 'POST', 'PUT']);

// 409 Conflict
throw new ConflictError('Email already exists', {
  email: '[email protected]'
});

// 422 Unprocessable Entity
throw new UnprocessableEntityError('Validation failed', {
  email: 'Invalid email format',
  age: 'Must be 18 or older'
});

// 429 Too Many Requests
throw new TooManyRequestsError('Rate limit exceeded', 60); // retry after 60 seconds

Server Errors (5xx)

import {
  InternalServerError, // 500
  NotImplementedError, // 501
  BadGatewayError,     // 502
  ServiceUnavailableError, // 503
  GatewayTimeoutError  // 504
} from '@geekmidas/errors';

// 500 Internal Server Error
throw new InternalServerError('Database connection failed');

// 501 Not Implemented
throw new NotImplementedError('Feature not yet implemented');

// 502 Bad Gateway
throw new BadGatewayError('Upstream server error');

// 503 Service Unavailable
throw new ServiceUnavailableError('Maintenance in progress', 300); // retry after 5 minutes

// 504 Gateway Timeout
throw new GatewayTimeoutError('Upstream server timeout');

Error Factories

Use convenient factory functions for creating errors:

import { createError } from '@geekmidas/errors';

// Short, descriptive method names
throw createError.badRequest('Invalid input');
throw createError.notFound('User not found');
throw createError.unauthorized('Invalid token');
throw createError.forbidden('Access denied');
throw createError.conflict('Resource already exists');
throw createError.internalServerError('Something went wrong');

// With details
throw createError.notFound('User not found', { userId: '123' });
throw createError.badRequest('Validation failed', {
  errors: ['Invalid email', 'Password too short']
});

Generic Error Factory

Create errors dynamically with type-safe options:

import { createHttpError } from '@geekmidas/errors';

// TypeScript knows which options are valid for each status code
throw createHttpError(404, 'Not found');
throw createHttpError(429, 'Rate limited', { retryAfter: 60 });
throw createHttpError(422, 'Validation failed', {
  validationErrors: {
    email: 'Invalid format',
    age: 'Must be 18+'
  }
});

Type Guards

Check error types at runtime:

import {
  isHttpError,
  isClientError,
  isServerError,
  NotFoundError
} from '@geekmidas/errors';

try {
  // some code
} catch (error) {
  if (isHttpError(error)) {
    console.log(`HTTP ${error.statusCode}: ${error.message}`);
    console.log('Details:', error.details);
  }

  if (isClientError(error)) {
    // 4xx errors - client's fault
    console.log('Client error:', error.message);
  }

  if (isServerError(error)) {
    // 5xx errors - server's fault
    console.error('Server error:', error.message);
    // Alert monitoring system
  }

  if (error instanceof NotFoundError) {
    // Specific error type
    console.log('Resource not found');
  }
}

Error Wrapping

Wrap unknown errors into HTTP errors:

import { wrapError } from '@geekmidas/errors';

try {
  await someOperation();
} catch (error) {
  // Wrap unknown error as 500
  throw wrapError(error);

  // Or wrap with specific status and message
  throw wrapError(error, 503, 'Service temporarily unavailable');
}

Error Serialization

Serialize errors to JSON:

import { NotFoundError } from '@geekmidas/errors';

const error = new NotFoundError('User not found', { userId: '123' });

// Get JSON representation
const json = error.toJSON();
// {
//   name: 'NotFoundError',
//   message: 'User not found',
//   statusCode: 404,
//   statusMessage: 'Not Found',
//   details: { userId: '123' },
//   stack: '...'
// }

// Get error body for HTTP response
const body = error.body;
// JSON string: '{"message":"User not found","details":{"userId":"123"}}'

Error Cause Chaining

Chain errors using ES2022 error cause:

import { InternalServerError } from '@geekmidas/errors';

try {
  await database.connect();
} catch (originalError) {
  throw new InternalServerError('Failed to connect to database', {
    cause: originalError,
    details: { host: 'localhost', port: 5432 }
  });
}

Express Middleware

Handle errors in Express applications:

import { isHttpError } from '@geekmidas/errors';
import type { Request, Response, NextFunction } from 'express';

function errorHandler(
  error: unknown,
  req: Request,
  res: Response,
  next: NextFunction
) {
  if (isHttpError(error)) {
    res.status(error.statusCode).json({
      error: {
        message: error.message,
        code: error.code,
        details: error.details
      }
    });
  } else {
    // Unknown error
    console.error('Unexpected error:', error);
    res.status(500).json({
      error: {
        message: 'Internal Server Error'
      }
    });
  }
}

// Use in Express app
app.use(errorHandler);

Hono Middleware

Handle errors in Hono applications:

import { Hono } from 'hono';
import { isHttpError } from '@geekmidas/errors';

const app = new Hono();

app.onError((error, c) => {
  if (isHttpError(error)) {
    return c.json(
      {
        error: {
          message: error.message,
          code: error.code,
          details: error.details
        }
      },
      error.statusCode
    );
  }

  console.error('Unexpected error:', error);
  return c.json(
    { error: { message: 'Internal Server Error' } },
    500
  );
});

Custom Error Classes

Extend base classes for custom errors:

import { HttpError } from '@geekmidas/errors';

export class CustomBusinessError extends HttpError {
  constructor(message?: string, details?: any) {
    super(400, message, { details, code: 'BUSINESS_RULE_VIOLATION' });
  }
}

// Usage
throw new CustomBusinessError('Cannot delete user with active orders', {
  userId: '123',
  activeOrders: 5
});

Error Context

Add context to errors for better debugging:

import { NotFoundError } from '@geekmidas/errors';

function getUserById(id: string) {
  const user = database.findUser(id);

  if (!user) {
    throw new NotFoundError('User not found', {
      userId: id,
      requestId: req.headers['x-request-id'],
      timestamp: new Date().toISOString(),
      source: 'getUserById'
    });
  }

  return user;
}

HTTP Status Codes

Use the HttpStatusCode enum for type-safe status codes:

import { HttpStatusCode } from '@geekmidas/errors';

// Success
HttpStatusCode.OK                 // 200
HttpStatusCode.CREATED            // 201
HttpStatusCode.NO_CONTENT         // 204

// Redirection
HttpStatusCode.MOVED_PERMANENTLY  // 301
HttpStatusCode.NOT_MODIFIED       // 304

// Client Errors
HttpStatusCode.BAD_REQUEST        // 400
HttpStatusCode.UNAUTHORIZED       // 401
HttpStatusCode.FORBIDDEN          // 403
HttpStatusCode.NOT_FOUND          // 404
HttpStatusCode.CONFLICT           // 409
HttpStatusCode.UNPROCESSABLE_ENTITY // 422
HttpStatusCode.TOO_MANY_REQUESTS  // 429

// Server Errors
HttpStatusCode.INTERNAL_SERVER_ERROR // 500
HttpStatusCode.SERVICE_UNAVAILABLE   // 503

Best Practices

1. Use Specific Error Classes

// ❌ Don't use generic Error
throw new Error('User not found');

// ✅ Use specific HTTP error
throw new NotFoundError('User not found', { userId: '123' });

2. Include Helpful Details

// ❌ Minimal information
throw new BadRequestError('Invalid input');

// ✅ Include context
throw new BadRequestError('Invalid email format', {
  field: 'email',
  value: userInput,
  expectedFormat: '[email protected]'
});

3. Use Type Guards

// ❌ Assume error type
catch (error: any) {
  console.log(error.statusCode); // Unsafe
}

// ✅ Check error type
catch (error) {
  if (isHttpError(error)) {
    console.log(error.statusCode); // Safe
  }
}

4. Chain Errors

// ✅ Preserve original error context
try {
  await database.query();
} catch (originalError) {
  throw new InternalServerError('Database query failed', {
    cause: originalError,
    query: 'SELECT * FROM users'
  });
}

TypeScript Types

import type {
  HttpError,
  HttpErrorOptions,
  HttpErrorConstructor
} from '@geekmidas/errors';

// Options for creating errors
interface HttpErrorOptions {
  statusMessage?: string;
  details?: any;
  code?: string;
  cause?: Error;
}

// Constructor type for factory patterns
type HttpErrorConstructor = new (
  message?: string,
  options?: HttpErrorOptions
) => HttpError;

License

MIT

版本与发布记录

@geekmidas/errors 共发布 199 个版本,首次发布于 2025/10/20;过去 12 个月发布了 198 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/errors 的常见问题

@geekmidas/errors 是什么?

Type-safe HTTP error classes with full TypeScript support, providing structured error handling for REST APIs and HTTP-based applications.

如何安装 @geekmidas/errors?

在项目目录运行 npm install @geekmidas/errors,或使用 pnpm add / yarn add / bun add。

@geekmidas/errors 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geekmidas/errors 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geekmidas/errors 可以商用吗?

@geekmidas/errors 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@geekmidas/errors 的下载量有多少?

根据 npm 官方下载统计,@geekmidas/errors 在 2026/10/16 – 2026/11/14 这 30 天内被下载 15,098 次,日均约 503 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geekmidas/errors 还在维护吗?

最新版本 9.6.1 发布于 2026/11/16(今天);至今共发布 199 个版本,其中过去 12 个月发布了 198 个;首次发布于 2025/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。