需要在项目所有 trycatch 中加个日志收集。
![]() | 1 newghost 2019-08-01 08:55:22 +08:00 js 是一般不写 try/catch,一般采用 error first,error 永远是回调的第一个参数,有 error 就用 console.log/ console.error 输出,只要把 console 重写到文件里就行。 |
![]() | 2 MuscleOf2016 OP @newghost 是的,不过像我现在遇到的情况有什么好的解决办法尼,代码已经没办法改了,准备用工具去遍历注入的。用正则? |
不知道 Error 类能不能加私货。 |
![]() | 4 cctv1005s927 2019-08-01 09:01:40 +08:00 @newghost 不一定吧..从 async / await 出来之后.. try catch 就用得很多了.. |
![]() | 5 Xxss 2019-08-01 09:15:35 +08:00 via Android try { // ... } catch (e) { // ... } finally { // record log here } 试试加一个 finally 块? |
![]() | 6 maichael 2019-08-01 09:16:50 +08:00 如果不换 try-catch 的写法的话,没办法。 我的做法是所有 catch 都有一个 console.error,然后重写 console.error。 |
![]() | 7 lymanliu 2019-08-01 09:18:25 +08:00 写个 webpack 插件,编译的时候注入,就好了吧 |
8 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); }) |
![]() | 9 MuscleOf2016 OP @sunzongzheng catch 的异常都处理过了,会走 onerror? |
10 sunzongzheng 2019-08-01 09:52:32 +08:00 @MuscleOf2016 #9 不会 |
![]() | 11 imlinhanchao 2019-08-01 09:55:32 +08:00 ![]() code.replace(/(\}\s*catch\(\s*(\w+)\s*\)\s*{)/mg, "$1\nlogfuntion($2);\n"); |
![]() | 12 Torpedo 2019-08-01 10:01:47 +08:00 你需要一个 babel 插件 |
![]() | 13 MuscleOf2016 OP @Torpedo 哪个有推荐不 |
![]() | 14 Torpedo 2019-08-01 10:04:29 +08:00 @newghost 怎么就不写 try catch 了? err first 只是一种风格,用 async await 不就要写 try catch 了? 而且本身程序必然有错误捕获的模块,难道不用 try catch ? |
![]() | 15 Torpedo 2019-08-01 10:13:43 +08:00 ![]() @MuscleOf2016 搜下,或者自己写个。https://github.com/darkyndy/babel-plugin-auto-logger 我觉得你还是代码里分哪些是异常,哪些是错误 。设计下结构。统一捕获一下 |
![]() | 16 otakustay 2019-08-01 10:16:32 +08:00 ![]() @newghost first error 是 callback 的模式,同步不用 callback 肯定是 try/catch,异步 js 玩 Promise 多好多年了也还是 try/catch …… 要重写是不可能的,上 babel 搞定还是比较容易的 |
![]() | 17 nigelvon 2019-08-01 10:17:56 +08:00 ![]() 整个项目查找替换一下,catch 里面执行上报的方法,也就 1 分钟的事儿。 |
![]() | 18 mystorp 2019-08-01 10:33:34 +08:00 via Android ![]() jscodeshift ?原理就是遍历 ast,查找 try catch。并加上自己的 log 代码。楼上说的 babel 插件也是类似的原理。不过,我觉得 17 楼的回答也很有意义,看怎么选择了 |
19 jifengg 2019-08-02 12:39:18 +08:00 via Android catch 中是用什么记录异常的,如果是 console.error,那就重写它。评估一下不要对现有系统有影响就行。 可别说 catch 里面连打印异常都没有。 |