@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/ 构造 - 在终点使用这些错误分类
- @geekmidas/ 客户端 - 在客户端处理这些错误
- @ geekmidas/ logger (英语) - 有结构上下文的日志错误
许可证
麻省理工学院