# 【JavaScript】常见报错 & 捕获方法(不只是try catch)

常见报错类型

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解码错误

处理 encodeURIdecodeURI 时传了非法字符,就会错。

示例

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.
URIErrorURI 函数参数非法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);
});

捕获总结

ConceptPurposeExample
try…catchRun risky code and handle errorstry { risky() } catch (err) { handle(err) }
throwCreate your own error for invalid statesthrow new Error("Invalid input")
finallyAlways runs, useful for cleanupfinally { cleanup() }
Async errorsUse .catch for promisesfetch().then().catch()
Async/awaitWrap with try...catchtry { await risky() } catch (err) {}

参考

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors
  2. https://www.atatus.com/blog/do-you-know-javascript-errors-that-could-happen
  3. https://dev.to/sadanandgadwal/the-ultimate-guide-to-error-handling-in-javascript-try-catch-throwing-and-real-world-practices-2kca
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值