错误 Handling
try/catch/最后, 自定义错误类型, and graceful recovery for sync and 异步 failures.
你将学到
- try/catch/最后 for synchronous 错误 handling
- Throwing and catching 错误对象
- 创建自定义错误 subclasses for 特定情况
- Handling 异步错误使用 try/catch 围绕等待
- 全局错误处理函数 and unhandled rejection 监听器
概念讲解
try / catch / finally
try wraps code that might throw. catch receives the thrown value if an error occurs. 最后 runs whether or not an error was thrown, making it the place for cleanup (closing files, releasing locks). In modern JavaScript, catch can omit the binding (catch { }) when you do not need the error object. Only throw 错误 objects — throwing strings or numbers loses the stack trace.
The Error Object
The built-in 错误 has a 消息, a name, and a stack property (non-standard but widely supported). JavaScript provides subclasses: TypeError, RangeError, SyntaxError, ReferenceError, URIError, and EvalError. Catching by type lets you handle different failures differently — check instanceof in the catch block.
Custom Errors
For application-specific failures, extend 错误 to create a named subclass. Set 这个.name and call super(消息) in the constructor. Custom errors make it easy to distinguish a "不找到" from a "validation 失败" at the catch site, and they carry extra fields (like a status code) that generic errors do not.
Async Error Handling
With async/await, errors are caught with the same try/catch — 等待 throws when a promise rejects. For promise chains, use .catch(). Always handle rejections: an unhandled rejection can crash Node.js (since v15) and logs warnings in browsers. Listen with 处理.on('unhandledRejection') in Node or window.addEventListener('unhandledrejection') in browsers.
Global Handlers
Some errors escape every try/catch — errors in event listeners, timers, or top-level code. Register global handlers as a safety net to log and report them, but do not use them as your primary strategy. The goal is to handle errors as close to their source as possible, where you have the context to recover meaningfully.
示例代码
// Custom error subclass with extra context
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class NotFoundError extends Error {
constructor(resource) {
super(`${resource} not found`);
this.name = "NotFoundError";
}
}
// Throwing and catching by type
function findUser(id) {
if (typeof id !== "number") throw new ValidationError("id", "must be a number");
if (id < 1) throw new ValidationError("id", "must be positive");
if (id > 100) throw new NotFoundError("User");
return { id, name: "Ada" };
}
try {
const user = findUser(999);
console.log(user);
} catch (e) {
if (e instanceof ValidationError) {
console.log(`Validation failed on '${e.field}': ${e.message}`);
} else if (e instanceof NotFoundError) {
console.log("Not found:", e.message);
} else {
throw e; // re-throw unknown errors
}
} finally {
console.log("lookup complete");
}
// Async error handling with try/catch
async function safeFetch(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (e) {
console.error("Fetch failed:", e.name, e.message);
return null;
}
}
// Global safety net (browser)
window.addEventListener("unhandledrejection", (e) => {
console.error("Unhandled rejection:", e.reason);
});
Shows 自定义错误 subclasses 使用 extra 字段, throwing and catching 通过类型使用 instanceof, re-throwing unknown 错误, 最后 for cleanup, 异步错误 handling, and 全局 unhandledrejection 监听器.
动手试一试
- HTTP 请求 Tester
触发 HTTP 错误 and 练习 catching 它们通过状态.
- HTTP 状态 Codes
映射状态 codes 到自定义错误类型 in 你的处理函数.
常见错误
错误写法
Throwing 字符串 or 数字相反的 错误对象
正确做法
总是 throw 新错误('消息'). 字符串 and 数字有 否 stack trace and cannot 是 caught 通过类型使用 instanceof. Use 自定义错误 subclasses for 特定情况.
错误写法
Catching 错误也 broadly and hiding 真实 bugs
正确做法
做不 wrap 整个函数 in try/catch 那个 silently 返回空. Catch 特定错误类型, handle 什么你 expect, and re-throw unknown 错误所以真实 bugs surface 相反的 是 swallowed.
相关资源
相关速查表
- JavaScript Cheatsheet
try/catch, 自定义错误, and 异步错误 handling 模式.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。