name: error-handling description: 在整个应用程序中实现一致的错误处理。 在添加try-catch块、错误边界或自定义错误类时使用。
错误处理技能
目的
确保一致、信息丰富的错误处理。
后端错误处理
自定义错误类
// templates/error-class.ts
export class AppError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500,
public details?: unknown
) {
super(message);
this.name = 'AppError';
}
}
export class ValidationError extends AppError {
constructor(message: string, details?: unknown) {
super('VALIDATION_ERROR', message, 400, details);
}
}
export class NotFoundError extends AppError {
constructor(resource: string) {
super('NOT_FOUND', `${resource} not found`, 404);
}
}
错误处理中间件
function errorHandler(err, req, res, next) {
logger.error(err);
if (err instanceof AppError) {
return res.status(err.statusCode).json({
error: {
code: err.code,
message: err.message,
details: err.details
}
});
}
return res.status(500).json({
error: {
code: 'INTERNAL_ERROR',
message: '发生意外错误'
}
});
}
前端错误处理
参考:patterns/frontend-errors.md
错误边界
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
logError(error, info);
}
render() {
if (this.state.hasError) {
return <ErrorFallback onReset={() => this.setState({ hasError: false })} />;
}
return this.props.children;
}
}
异步错误处理
async function fetchWithError<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
const error = await response.json();
throw new ApiError(error.code, error.message);
}
return response.json();
}
日志记录指南
| 级别 | 用途 |
|---|---|
| error | 异常、失败 |
| warn | 可恢复的问题 |
| info | 重要事件 |
| debug | 开发信息 |