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); }
上傳釘釘機器人
-
第一步:添加自定義機器人
-
第二步:復(fù)制Webhook接口炕横,自定義安全設(shè)置等
- 第三步:捕獲到錯誤后通過接口上傳到釘釘消息群
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模式
??打包之后發(fā)現(xiàn)捕獲的錯誤代碼定位不全椿肩,比如像這種的??聂喇,
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
玩讳,代碼被壓縮了
相關(guān)jsbundle打包命令
react-native bundle <flag>
可詳見 https://github.com/react-native-community/cli/blob/master/docs/commands.md#bundle