DevToolBox免费
博客

JavaScript错误处理最佳实践:try/catch、异步错误、自定义错误

11分钟作者 DevToolBox

健壮的错误处理是区分生产级 JavaScript 和脆弱演示的关键。本指南涵盖 try/catch 模式异步错误处理自定义错误类和生产级错误管理策略。

try/catch 基础

try/catch/finally 块是 JavaScript 同步错误处理的基础。

// try/catch/finally fundamentals

// Basic structure
try {
  const data = JSON.parse(userInput); // Can throw SyntaxError
  processData(data);
} catch (error) {
  if (error instanceof SyntaxError) {
    console.error('Invalid JSON:', error.message);
  } else {
    throw error; // Re-throw errors you can't handle here
  }
} finally {
  cleanup(); // Always runs — use for resource cleanup
}

// What catch does NOT catch:
// 1. Errors in async callbacks (use async/await instead)
// 2. Errors in setTimeout/setInterval
// 3. Errors in event handlers

// Wrong: setTimeout error is not caught
try {
  setTimeout(() => {
    throw new Error('This is NOT caught by outer try/catch');
  }, 100);
} catch (e) {
  // This never runs
}

// Right: wrap async code
setTimeout(() => {
  try {
    throw new Error('This IS caught');
  } catch (e) {
    console.error(e);
  }
}, 100);

// Distinguishing error types
function handleError(error) {
  if (error instanceof TypeError) {
    // Null dereference, wrong type
  } else if (error instanceof RangeError) {
    // Array out of bounds, recursion limit
  } else if (error instanceof NetworkError) {
    // Custom: network failure
  } else {
    // Unknown: re-throw
    throw error;
  }
}

async/await 错误处理

async 函数返回 Promise,因此错误需要用不同的方式捕获。

// Async/Await Error Handling

// 1. Basic async error handling
async function fetchUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Request was aborted');
      return null;
    }
    throw error; // Re-throw for caller to handle
  }
}

// 2. Handling multiple async operations
async function loadDashboard(userId) {
  // Run in parallel, catch errors individually
  const [user, posts, stats] = await Promise.allSettled([
    fetchUser(userId),
    fetchPosts(userId),
    fetchStats(userId),
  ]);

  return {
    user: user.status === 'fulfilled' ? user.value : null,
    posts: posts.status === 'fulfilled' ? posts.value : [],
    stats: stats.status === 'fulfilled' ? stats.value : {},
    errors: [user, posts, stats]
      .filter(r => r.status === 'rejected')
      .map(r => r.reason),
  };
}

// 3. Async error handling utility
async function tryCatchAsync<T>(
  promise: Promise<T>
): Promise<[T | null, Error | null]> {
  try {
    const data = await promise;
    return [data, null];
  } catch (error) {
    return [null, error instanceof Error ? error : new Error(String(error))];
  }
}

// Usage: avoids nested try/catch
const [user, error] = await tryCatchAsync(fetchUser(id));
if (error) {
  console.error('Failed to fetch user:', error.message);
  return;
}
console.log(user.name);

自定义错误类

创建自定义错误类可以实现结构化错误处理、更好的堆栈跟踪和程序化错误类型检查。

// Custom Error Classes

class AppError extends Error {
  public readonly code: string;
  public readonly statusCode: number;
  public readonly isOperational: boolean;

  constructor(
    message: string,
    code: string,
    statusCode = 500,
    isOperational = true
  ) {
    super(message);
    this.name = this.constructor.name;
    this.code = code;
    this.statusCode = statusCode;
    this.isOperational = isOperational;

    // Maintains proper prototype chain (important for instanceof)
    Object.setPrototypeOf(this, new.target.prototype);

    // Captures stack trace (V8 only)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

class ValidationError extends AppError {
  public readonly fields: Record<string, string[]>;

  constructor(message: string, fields: Record<string, string[]> = {}) {
    super(message, 'VALIDATION_ERROR', 400);
    this.fields = fields;
  }
}

class NotFoundError extends AppError {
  constructor(resource: string, id: string | number) {
    super(`${resource} with id ${id} not found`, 'NOT_FOUND', 404);
  }
}

class NetworkError extends AppError {
  public readonly url: string;

  constructor(message: string, url: string) {
    super(message, 'NETWORK_ERROR', 503);
    this.url = url;
  }
}

// Usage
function findUser(id: number) {
  const user = db.find(id);
  if (!user) throw new NotFoundError('User', id);
  return user;
}

// Error type checking
try {
  findUser(999);
} catch (error) {
  if (error instanceof NotFoundError) {
    res.status(404).json({ error: error.message, code: error.code });
  } else if (error instanceof ValidationError) {
    res.status(400).json({ error: error.message, fields: error.fields });
  } else {
    // Unknown error — log and return 500
    logger.error('Unexpected error', { error });
    res.status(500).json({ error: 'Internal server error' });
  }
}

全局错误处理器

一些错误会逃过本地的 try/catch 块。全局处理器是防止静默失败的最后一道防线。

// Global Error Handlers

// Browser: uncaught synchronous errors
window.onerror = (message, source, lineno, colno, error) => {
  console.error('Uncaught error:', { message, source, lineno, colno, error });
  reportToSentry(error);
  return true; // Prevents default browser error dialog
};

// Browser: unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
  reportToSentry(event.reason);
  event.preventDefault(); // Prevents console error
});

// Node.js: uncaught exceptions
process.on('uncaughtException', (error) => {
  console.error('Uncaught exception:', error);
  reportToSentry(error);
  // Exit after logging — cannot safely continue after uncaughtException
  process.exit(1);
});

// Node.js: unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection at:', promise, 'reason:', reason);
  reportToSentry(reason instanceof Error ? reason : new Error(String(reason)));
});

// Express.js: error middleware (must have 4 params)
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  const isOperational = err.isOperational || false;

  if (!isOperational) {
    // Unexpected error — log full details
    console.error('Unexpected error:', err);
    reportToSentry(err, { url: req.url, method: req.method });
  }

  res.status(statusCode).json({
    error: {
      message: isOperational ? err.message : 'Internal server error',
      code: err.code || 'INTERNAL_ERROR',
    },
  });
});

常见问题

我应该捕获每一个错误吗?

不应该。只捕获你能在当前层级有意义地处理的错误。捕获一切并吞掉错误比让它们传播更糟糕。

throw 和 throw new Error() 有什么区别?

JavaScript 中可以抛出任何值,但抛出非 Error 对象会丢失堆栈跟踪。始终使用 throw new Error() 来保留调用栈。

如何处理 Promise.all() 中的错误?

Promise.all() 会在任何一个 Promise 拒绝时立即拒绝。使用 Promise.allSettled() 可以获取所有 Promise 的结果。

错误消息应该包含什么?

错误消息应该具有可操作性和针对性。永远不要在错误消息中包含敏感数据(密码、令牌)。

相关工具

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

{ }JSON FormatterJSJavaScript Minifier

相关文章

JavaScript Promises 和 Async/Await 完全指南

掌握 JavaScript Promises 和 async/await:创建、链式调用、Promise.all、错误处理和并发策略。

JavaScript 闭包详解:作用域、内存与实战模式

2026年JavaScript闭包深度指南:词法作用域、闭包内存影响、记忆化、模块模式与柯里化实战。

React Hooks 完全指南

通过实际示例掌握 React Hooks。