首页 > 解决方案 > Expo React Native - 如何使用 ErrorRecovery?

问题描述

当前的Expo ErrorRecovery 文档没有提供任何使用ErrorRecovery.setRecoveryProps().

如果您知道如何使用Managed workflow来捕获 JS 错误,请告诉我。

谢谢

标签: react-nativeexpo

解决方案


我试了一下:

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Button } from "react-native-paper";
import * as ErrorRecovery from "expo-error-recovery";

export default function App({ exp }) {
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{JSON.stringify(exp.errorRecovery)}</Text>
      <Button
        onPress={() => {
          ErrorRecovery.setRecoveryProps({ info: "User pressed crash button" });
          throw "Crash!";
        }}
      >
        Crash!
      </Button>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center"
  }
});

当您最初加载应用程序时,exp.errorRecovery将为空。如果您单击“ Crash!”按钮并重新加载,那么exp.errorRecovery将包含您设置的任何内容setRecoveryProps()

我认为这个想法是你可以setRecoveryProps()让你的应用程序知道它崩溃了,并可能提供一些关于崩溃前发生的事情的上下文。不过,我从未使用过它,所以我不确定什么是好的用例。

编辑:

以上内容可能不是那么有用,但您可以将其与此处显示的方法(使用全局错误处理程序)结合起来,将有关崩溃的一些信息传递给重新加载的应用程序:

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Button } from "react-native-paper";
import * as ErrorRecovery from "expo-error-recovery";

const defaultErrorHandler = ErrorUtils.getGlobalHandler();

const globalErrorHandler = (err, isFatal) => {
  console.log("globalErrorHandler called!");
  ErrorRecovery.setRecoveryProps({ info: err });
  defaultErrorHandler(err, isFatal);
};

ErrorUtils.setGlobalHandler(globalErrorHandler);

export default function App({ exp }) {
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{JSON.stringify(exp.errorRecovery)}</Text>
      <Button
        onPress={() => {
          throw "Crash!";
        }}
      >
        Crash!
      </Button>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center"
  }
});

推荐阅读