常见报错类型
RangeError 范围错误
当参数值不在合法区间,就得 RangeError
示例场景:
-
toFixed()参数超出范围:(1.23).toFixed(1000); // 报 RangeError -
创建非法长度数组:
new Array(-1); // 报 RangeError: Invalid array length -
递归层级太高也会触发:
function recurse(){ recurse(); } recurse(); // “Maximum call stack size exceeded” -
日期错误:
new Date("2024-02-30"); // 报 RangeError: invalid date 或 invalid time value -
BigInt 除以零:
BigInt(10) / BigInt(0); // RangeError: BigInt division by zero
ReferenceError 引用错误
试图访问未声明的变量
示例:
console.log(userAge); // userAge 未定义,会报 ReferenceError: userAge is not defined
SyntaxError 语法错误
通常因为语法格式错,导致 JS 在“读不通”代码时直接抛错。
示例:
function foo(bar { // 括号没闭合
return bar;
}
控制台一般会提示 SyntaxError: Unexpected token {}`。
也有诸如漏掉引号、花括号、括号等情况
TypeError 类型错误
操作类型不匹配,就报 TypeError。就像对数字用 .toUpperCase(),大脑短路。
示例:
let num = 1;
num.toUpperCase(); // 数字没有 toUpperCase 方法
控制台会说 TypeError: num.toUpperCase is not a function
URIError URL解码错误
处理 encodeURI、decodeURI 时传了非法字符,就会错。
示例:
decodeURIComponent("%"); // 抛 URIError
EvalError / InternalError — 特殊错误类型
- EvalError:基本不会在现代 JS 中触发(遗留兼容
- InternalError:通常是 JS 引擎内部的炸裂,比如递归次数爆炸导致“too much recursion”
报错总结
| 错误类型 | 触发场景示例 | 报错内容(常见) |
|---|---|---|
| SyntaxError | 漏括号、漏引号等语法问题 | Unexpected token |
| ReferenceError | 使用未声明变量 | X is not defined |
| TypeError | 对类型不支持的操作(如数字 .toUpperCase()) | X is not a function |
| RangeError | 数值或参数不在允许范围(如数组负长度、toFixed 大范围) | Invalid array length / precision etc. |
| URIError | URI 函数参数非法 | URIError: malformed URI sequence |
| InternalError | 引擎内部问题,如递归太深 | too much recursion |
| EvalError | 老旧 eval 问题(现代很少遇到) | — |
错误捕获方法
try…catch 捕获示范
最常见的
try {
// 放入可能抛错的“危险代码”
} catch (e) {
// 抓捕错误,e 是 Error 对象或任意被抛出的内容
} finally {
// 无论是否有错,都会执行
}
finally是你要做“清扫”操作(如关闭文件、释放资源、隐藏 loading 等)的最佳地点——无论有没有异常,它都跑得起来throw有时,你的程序会检测到 JS 引擎本身不会认为是错误的问题。例如,一个数字可能是负数,但实际上它不应该是负数。为了处理这种情况,你可以抛出你自己的错误。
有人在 StackOverflow 上推荐这样写来区分错误类型:
“只处理特定错误,其他的往上扔
Promise.catch()(then/catch)
fetch("https://api.example.com/data")
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error("捕获到异常:", err));
这种链式写法简单,但层级深了就容易乱
顶层捕获(Node.js/浏览器全局)
浏览器
window.addEventListener("unhandledrejection", (event) => {
console.error("未捕获的 Promise 异常:", event.reason);
});
nodejs
process.on("unhandledRejection", (reason, promise) => {
console.error("未捕获的 Promise 异常:", reason);
});
捕获总结
| Concept | Purpose | Example |
|---|---|---|
| try…catch | Run risky code and handle errors | try { risky() } catch (err) { handle(err) } |
| throw | Create your own error for invalid states | throw new Error("Invalid input") |
| finally | Always runs, useful for cleanup | finally { cleanup() } |
| Async errors | Use .catch for promises | fetch().then().catch() |
| Async/await | Wrap with try...catch | try { await risky() } catch (err) {} |
参考
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors
- https://www.atatus.com/blog/do-you-know-javascript-errors-that-could-happen
- https://dev.to/sadanandgadwal/the-ultimate-guide-to-error-handling-in-javascript-try-catch-throwing-and-real-world-practices-2kca
2715

被折叠的 条评论
为什么被折叠?



