JavaScript/react 新手,但不是编程新手。
我想构建一个强大的移动应用程序,可能会出现意外错误;在某些情况下,try/catch 不起作用,例如内部的异步调用。
我想要一个全局错误处理程序来尝试捕获错误,以便我可以记录/报告它们,然后找出如何解决根本问题。
我尝试过 react-native-exception-handler,但无法让它工作。
https://github.com/a7ul/react-native-exception-handler
我通过新文件夹创建了一个新项目,react-native init 并在 app.js 上创建了一个按钮来抛出错误。
app.js 的开头是:
import React from 'react';
import type {Node} from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Button
} from 'react-native';
import {
Colors,
Header,
} from 'react-native/Libraries/NewAppScreen';
import {setJSExceptionHandler, getJSExceptionHandler} from 'react-native-exception-handler';
import { setNativeExceptionHandler } from "react-native-exception-handler";
setJSExceptionHandler((error, isFatal) => {
// This is your custom global error handler
// You do stuff like show an error dialog
// or hit google analytics to track crashes
// or hit a custom api to inform the dev team.
console.log("setJSExceptionHandler", isFatal, error)
}, true);
setNativeExceptionHandler((exceptionString) => {
// This is your custom global error handler
// You do stuff likehit google analytics to track crashes.
// or hit a custom api to inform the dev team.
//NOTE: alert or showing any UI change via JS
//WILL NOT WORK in case of NATIVE ERRORS.
console.log("setNativeExceptionHandler", exceptionString)
},false,true);
在文件的应用部分,例如:
const App: () => Node = () => {
然后我有按钮推送的处理程序代码:
const test2Press = async () => {
console.log("test2 pressed")
throw new Error("catch me")
}
当我按下这个按钮时,我会登录到控制台:
LOG test2 pressed
WARN Possible Unhandled Promise Rejection (id: 0):
Error: catch me
接下来是看起来像堆栈跟踪的内容。
这向我表明错误处理代码不起作用,否则我会在控制台日志中看到“setJSExceptionHandler”。
我也试过运行这个库的示例程序 - https://github.com/a7ul/react-native-exception-handler-example - 但无法让它运行。到了“构建 99% > : app.installDebug 但似乎卡住了
谁能看到我做错了什么,或者应该以不同的方式发现这种错误吗?