React-Native 全局捕获JS运行时错误代码
react-native / polyfills / error-guard.js
使用global.ErrorUtils.setGlobalHandler
全局捕获错误以避免崩溃
if(!__DEV__){
global.ErrorUtils.setGlobalHandler(async (e, isFatal) => {
if (isFatal) {
e.name //错误类型
e.message //错误信息
e.componentStack||e.stack //错误代码定位
}
}
}
补充:
- isFatal
建议保留isFatal=true
的判断,尽管目前都是true
[1]
全局捕获未处理的Promise错误
react-native / Libraries / Promise.js
require('promise/setimmediate/rejection-tracking').enable({
onUnhandled:(id, error = {})=>{
console.log("全局捕获未处理的Promise错误",id,error)
console.log(error.name)
console.log(error.message)
console.log(error.componentStack||error.stack)
}
})
重启rn页面
- ios
NativeModules.BridgeReloader.reload()
- android
@ReactMethod public void reload() { Activity activity = getCurrentActivity(); Intent intent = activity.getIntent(); activity.finish(); activity.startActivity(intent); }
上传钉钉机器人
-
第一步:添加自定义机器人
-
第二步:复制Webhook接口,自定义安全设置等
- 第三步:捕获到错误后通过接口上传到钉钉消息群
if(!__DEV__){ fetch("https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx",{ method:"POST", headers:{ "Content-Type":"application/json" }, body:JSON.stringify({ "msgtype":"markdown", "markdown":{ "title":"前端代码报错", "text":"# <font color=\'#dd0000\'>前端代码报错</font> @13011112222 \n - **时间**: "+new Date().toLocaleString()+" \n - **版本**: `"+getRestfulUrlVersion()+"` \n\n``` \n"+e.name+":\n"+e.message+"\n"+(e.componentStack||e.stack)+" \n```", }, "at":{"atMobiles":["13011112222"],"isAtAll":false}}), }).then(res=>{}).catch(err=>{}) }
-
效果
SourceMap模式
⚠️打包之后发现捕获的错误代码定位不全,比如像这种的⬇️,
Invariant Violation:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
in P
in RCTView
in ScrollableTabView
in RCTView
in u
in Connect(u)
in ReceiveFile
in O
in RCTView
in w
in RCTView
in b
in PanGestureHandler
in ve
in GestureHandlerRootView
in Unknown
in b
in x
in Connect(x)
in y
in RCTView
in RCTView
in RCTView
in P
in w
in C
in RCTView
in RCTView
in C
in RCTView
in V
in C
in Unknown
in D
in R
in RCTView
in c
in o
in x
in RCTView
in RCTView
in f
in o
in RCTView
in RCTView
in c
in RCTView
in v
in RCTView
in RCTView
in x
是因为我们在打包jsbundle的时候没有开启sourceMap模式 --sourcemap-output
,代码被压缩了
相关jsbundle打包命令
react-native bundle <flag>
可详见 https://github.com/react-native-community/cli/blob/master/docs/commands.md#bundle