@geekmidas/errors

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

具有完整TypeScript支持的Type-seafe HTTP出错类,为REST API和基于HTTP的应用程序提供结构化出错处理.

中文使用文档
文档目录27 节
  1. 特征
  2. 安装
  3. 快速启动
  4. 基本用途
  5. 有错误细节
  6. 可用错误分类
  7. 客户端错误( 4xx)
  8. 服务器出错( 5xx)
  9. 错误工厂
  10. 通用错误厂
  11. 类型警卫
  12. 环绕错误
  13. 序列化错误
  14. 错误导致链条
  15. 表达式中件
  16. Hono 中间软件
  17. 自定义错误类
  18. 错误上下文
  19. HTTP 状态代码
  20. 最佳做法
  21. 1. 使用特定错误类别
  22. 2. 包括有益的细节
  23. 3. 使用类型警卫
  24. 4. 链条出错
  25. 类型脚本
  26. 相关软件包
  27. 许可证

@geekmidas/错误

具有完整TypeScript支持的Type-seafe HTTP出错类,为REST API和基于HTTP的应用程序提供结构化出错处理.

特征

  • 类型安全出错: 完整类型脚本支持,并带有适当的错误等级
  • HTTP 状态代码: 所有常见的 HTTP 错误的预建错误类
  • 结构化出错细节: 包含额外的上下文并调试信息
  • 错误工厂: 制造错误的方便工厂功能
  • 类型警卫: 运行时类型检查出错实例
  • JSON 序列化: 错误序列化的内置支持
  • 环绕错误: 将未知错误包入 HTTP 错误
  • 原因链: ES2022 错误导致错误链支持

安装

pnpm add @geekmidas/errors

快速启动

基本用途

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');

有错误细节

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'
});

可用错误分类

客户端错误( 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

服务器出错( 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');

错误工厂

使用方便的工厂函数来创建错误 :

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']
});

通用错误厂

用类型安全选项动态创建出错 :

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+'
  }
});

类型警卫

运行时检查出错类型 :

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');
  }
}

环绕错误

将未知错误包入 HTTP 错误 :

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');
}

序列化错误

将错误序列化为 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"}}'

错误导致链条

使用 ES2022 的链错误导致:

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 应用程序中的错误 :

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 中间软件

处理Hono应用程序中的错误 :

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
  );
});

自定义错误类

扩展自定义错误的基础类 :

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
});

错误上下文

添加上下文到错误中以更好地调试 :

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 状态代码

类型安全状态代码使用 HttpStatusCode enum :

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

最佳做法

1. 使用特定错误类别

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

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

2. 包括有益的细节

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

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

3. 使用类型警卫

// ❌ 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. 链条出错

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

类型脚本

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;

许可证

麻省理工学院

版本与发布记录

@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 是什么?

具有完整TypeScript支持的Type-seafe HTTP出错类,为REST API和基于HTTP的应用程序提供结构化出错处理.

如何安装 @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 和提交记录判断。