js 的 try catch 可以重写吗?

2019-08-01 08:47:19 +08:00
 MuscleOf2016

需要在项目所有 trycatch 中加个日志收集。

4990 次点击
所在节点    JavaScript
19 条回复
newghost
2019-08-01 08:55:22 +08:00
js 是一般不写 try/catch,一般采用 error first,error 永远是回调的第一个参数,有 error 就用 console.log/ console.error 输出,只要把 console 重写到文件里就行。
MuscleOf2016
2019-08-01 09:00:06 +08:00
@newghost 是的,不过像我现在遇到的情况有什么好的解决办法尼,代码已经没办法改了,准备用工具去遍历注入的。用正则?
whileFalse
2019-08-01 09:01:21 +08:00
不知道 Error 类能不能加私货。
cctv1005s927
2019-08-01 09:01:40 +08:00
@newghost 不一定吧..从 async / await 出来之后.. try catch 就用得很多了..
Xxss
2019-08-01 09:15:35 +08:00
try {
// ...
} catch (e) {
// ...
} finally {
// record log here
}

试试加一个 finally 块?
maichael
2019-08-01 09:16:50 +08:00
如果不换 try-catch 的写法的话,没办法。

我的做法是所有 catch 都有一个 console.error,然后重写 console.error。
lymanliu
2019-08-01 09:18:25 +08:00
写个 webpack 插件,编译的时候注入,就好了吧
sunzongzheng
2019-08-01 09:43:43 +08:00
browser: window.onerror = function(message, source, lineno, colno, error) { ... }
nodejs: process.on('uncaughtException', function(err) {
console.error('Error caught in uncaughtException event:', err);
})
MuscleOf2016
2019-08-01 09:45:21 +08:00
@sunzongzheng catch 的异常都处理过了,会走 onerror?
sunzongzheng
2019-08-01 09:52:32 +08:00
@MuscleOf2016 #9 不会
imlinhanchao
2019-08-01 09:55:32 +08:00
code.replace(/(\}\s*catch\(\s*(\w+)\s*\)\s*{)/mg, "$1\nlogfuntion($2);\n");
Torpedo
2019-08-01 10:01:47 +08:00
你需要一个 babel 插件
MuscleOf2016
2019-08-01 10:02:56 +08:00
@Torpedo 哪个有推荐不
Torpedo
2019-08-01 10:04:29 +08:00
@newghost 怎么就不写 try catch 了? err first 只是一种风格,用 async await 不就要写 try catch 了?
而且本身程序必然有错误捕获的模块,难道不用 try catch ?
Torpedo
2019-08-01 10:13:43 +08:00
@MuscleOf2016 搜下,或者自己写个。https://github.com/darkyndy/babel-plugin-auto-logger
我觉得你还是代码里分哪些是异常,哪些是错误 。设计下结构。统一捕获一下
otakustay
2019-08-01 10:16:32 +08:00
@newghost first error 是 callback 的模式,同步不用 callback 肯定是 try/catch,异步 js 玩 Promise 多好多年了也还是 try/catch ……

要重写是不可能的,上 babel 搞定还是比较容易的
nigelvon
2019-08-01 10:17:56 +08:00
整个项目查找替换一下,catch 里面执行上报的方法,也就 1 分钟的事儿。
mystorp
2019-08-01 10:33:34 +08:00
jscodeshift ?原理就是遍历 ast,查找 try catch。并加上自己的 log 代码。楼上说的 babel 插件也是类似的原理。不过,我觉得 17 楼的回答也很有意义,看怎么选择了
jifengg
2019-08-02 12:39:18 +08:00
catch 中是用什么记录异常的,如果是 console.error,那就重写它。评估一下不要对现有系统有影响就行。

可别说 catch 里面连打印异常都没有。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/588045

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX