App Center 當機 (React Native)

重要

Visual Studio App Center 已排定於 2025 年 3 月 31 日淘汰。 雖然您可以繼續使用 Visual Studio App Center,直到它完全淘汰為止,但有數個建議您考慮移轉至的建議替代方案。

深入瞭解支持時程表和替代方案。

App Center 當機會在每次您的應用程式當機時自動產生當機記錄。 記錄會先寫入裝置的記憶體,當使用者再次啟動應用程式時,損毀報告將會傳送至 App Center。 收集當機適用於 Beta 和即時應用程式,也就是提交至 Google Play 的 App。 當機記錄包含協助您修正損毀的重要資訊。

如果您尚未在應用程式中設定 SDK,請遵循 [使用者入門] 區段。

無論您使用 App Center 當機,請在檔案頂端新增下列匯入。

// Import App Center Crashes at the top of the file.
import Crashes from 'appcenter-crashes';

產生測試損毀

App Center 當機提供 API 來產生測試損毀,以便輕鬆測試 SDK。 此 API 只能在測試/Beta 應用程式中使用,而且不會在生產應用程式中執行任何動作。

Crashes.generateTestCrash();

也很容易產生 JavaScript 當機。 將下列這一行新增至您的程序代碼,這會擲回 JavaScript 錯誤並造成損毀。

throw new Error('This is a test javascript crash!');

提示

您的 React Native 應用程式必須在發行模式中編譯,才能將此損毀傳送至 App Center。

注意

目前,App Center 不支援來源對應,以統一 Android React Native 應用程式的 JavaScript 堆棧追蹤。

注意

最佳做法是避免使用字串值 (的 JavaScript throw 語句,例如: throw 'message') ,因為在此案例中,React Native 不會保留完整的 JavaScript 堆棧。 相反地, throw JavaScript Error (例如: throw Error('message')) 。

取得先前損毀的詳細資訊

App Center 當機有兩個 API,可讓您在應用程式損毀時取得詳細資訊。

應用程式在上一個會話中是否收到低記憶體警告?

在啟動 SDK 之後,您可以隨時檢查應用程式是否在上一個工作階段中收到記憶體警告:

const hadLowMemoryWarning = await Crashes.hasReceivedMemoryWarningInLastSession();

注意

在某些情況下,記憶體不足的裝置可能無法傳送事件。

應用程式在上一個會話中當機嗎?

在啟動 SDK 之後,您可以隨時檢查應用程式是否在上一次啟動時當機:

const didCrash = await Crashes.hasCrashedInLastSession();

如果您想要在發生當機之後調整應用程式的行為或 UI,這會很有用。 有些開發人員選擇向用戶顯示其他UI,或想要在發生當機之後連絡。

上次損毀的詳細數據

如果您的應用程式先前損毀,您可以取得上次損毀的詳細數據。

const crashReport = await Crashes.lastSessionCrashReport();

自訂 App Center 損毀的使用方式

App Center 當機提供回呼,讓開發人員在將損毀記錄傳送至 App Center 之前和時執行其他動作。

在 JavaScript 中處理損毀

為了讓 Crash.setListener 方法如預期般運作,您需要檢查應用程式是否已正確設定。

  1. 開啟項目的 ios/YourAppName/AppDelegate.m 檔案,並確認您有 [AppCenterReactNativeCrashes register]; ,而不是 [AppCenterReactNativeCrashes registerWithAutomaticProcessing];
  2. 開啟項目的 android/app/src/main/res/values/strings.xml 檔案,並確認 已 appCenterCrashes_whenToSendCrashes 設定為 ASK_JAVASCRIPT

此檔中會逐一討論事件接聽程式的所有不同回呼,但您必須設定一個事件接聽程式,一次定義所有回呼。

應該處理當機嗎?

如果您想要決定是否需要處理特定當機,請實作此回呼。 例如,您可能想要忽略系統層級損毀,而且您不想傳送至 App Center。

Crashes.setListener({

    shouldProcess: function (report) {
        return true; // return true if the crash report should be processed, otherwise false.
    },

    // Other callbacks must also be defined at the same time if used.
    // Default values are used if a method with return parameter isn't defined.
});

注意

若要使用該功能,您必須為當機服務正確設定應用程式。

這項功能取決於 JavaScript 中的處理損毀

如果用戶隱私權對您很重要,您應該先取得使用者確認,再將當機報告傳送至 App Center。 SDK 會公開回呼,告知 App Center 當機在傳送任何損毀報告之前,先等候使用者確認。

如果您選擇這樣做,您必須負責取得使用者的確認,例如透過具有下列其中一個選項的對話框提示: 永遠傳送傳送不要傳送。 根據輸入,您會告訴 App Center 損毀要執行的動作,然後會據以處理當機。

注意

SDK 不會顯示此對話框,應用程式必須提供自己的 UI 以要求使用者同意。

下列回呼示範如何告訴 SDK 在傳送當機之前等候使用者確認:

Crashes.setListener({

    shouldAwaitUserConfirmation: function (report) {

        // Build your own UI to ask for user consent here. SDK doesn't provide one by default.

        // Return true if you built a UI for user consent and are waiting for user input on that custom UI, otherwise false.
        return true;
    },

    // Other callbacks must also be defined at the same time if used.
    // Default values are used if a method with return parameter isn't defined.
});

如果您傳回 true,您的應用程式必須使用您自己的程式代碼來取得 (,) 使用者的許可權,並使用下列 API 以結果更新 SDK:

import Crashes, { UserConfirmation } from 'appcenter-crashes';

// Depending on the user's choice, call Crashes.notifyUserConfirmation() with the right value.
Crashes.notifyUserConfirmation(UserConfirmation.DONT_SEND);
Crashes.notifyUserConfirmation(UserConfirmation.SEND);
Crashes.notifyUserConfirmation(UserConfirmation.ALWAYS_SEND);

注意

若要使用這項功能,請針對損毀服務正確設定您的應用程式。 此功能取決於 JavaScript 中的處理損毀

取得損毀記錄傳送狀態的相關信息

有時候,您想要知道應用程式當機的狀態。 常見的使用案例是您可能想要顯示UI,告知使用者您的應用程式正在提交當機報告,或者,如果您的app在啟動後快速當機,您想要調整應用程式的行為,以確保可以提交當機記錄。 App Center 當機有三個不同的回呼,您可以在應用程式中用來通知發生什麼事。

若要這樣做,請在程式代碼中定義事件接聽程式,如下列範例所示:

Crashes.setListener({
    onBeforeSending: function (report) {
        // called after Crashes.process and before sending the crash.
    },
    onSendingSucceeded: function (report) {
        // called when crash report sent successfully.
    },
    onSendingFailed: function (report) {
        // called when crash report couldn't be sent.
    }

    // Other callbacks must also be defined at the same time if used.
    // Default values are used if a method with return parameter isn't defined.
});

所有回呼都是選擇性的。 您不需要在事件接聽程式物件中提供所有 3 種方法,例如,您只能 onBeforeSending實作 。

注意

若要使用該功能,您必須為當機服務正確設定應用程式。

這項功能取決於 JavaScript 中的處理損毀

注意

如果 Crashes.setListener 呼叫超過一次,則最後一個會勝出;它會覆寫先前由 設定的 Crashes.setListener接聽程式。

onSendingFailed接收表示發生無法復原的錯誤,例如發生 4xx 碼。 例如, 401 表示 appSecret 錯誤。

如果這是網路問題,則不會觸發此回呼。 在此情況下,SDK 會持續重試 (,並在網路連線關閉時暫停重試) 。 如果端點發生網路問題或中斷,且您重新啟動應用程式, onBeforeSending 則會在進程重新啟動后再次觸發。

將附件新增至損毀報告

您可以將二進位和文字附件新增至當機報表。 SDK 會連同當機一起傳送它們,讓您可以在 App Center 入口網站中看到它們。 在傳送先前應用程式啟動的預存損毀之前,會立即叫用下列回呼。 噹噹機發生時,不會叫用它。 請確定附件檔案 命名 minidump.dmp 為該名稱保留給迷你傾印檔案。 以下是如何將文字和影像附加至當機的範例:

import Crashes, { ErrorAttachmentLog } from 'appcenter-crashes';

Crashes.setListener({
    getErrorAttachments(report) {
        const textAttachment = ErrorAttachmentLog.attachmentWithText('Hello text attachment!', 'hello.txt');
        const binaryAttachment = ErrorAttachmentLog.attachmentWithBinary(`${imageAsBase64string}`, 'logo.png', 'image/png');
        return [textAttachment, binaryAttachment];
    }

    // Other callbacks must also be defined at the same time if used.
    // Default values are used if a method with return parameter isn't defined.
});

參數 fileName 是選擇性 (可以 null) ,而且只能在App Center入口網站中使用。 從入口網站中發生特定的當機情況,您可以看到附件並加以下載。 如果您指定檔名,將會是要下載的檔名,否則會產生檔名。

若要設定 getErrorAttachments 回呼以使用ES2017 async/await 函式,請改為傳回已完成的 Promise。 下列範例會以異步方式將文字和影像附加至當機:

import Crashes, { ErrorAttachmentLog } from 'appcenter-crashes';

Crashes.setListener({
    getErrorAttachments(report) {
        return (async () => {
            const textContent = await readTextFileAsync(); // use your async function to read text file
            const binaryContent = await readBinaryFileAsync(); // use your async function to read binary file
            const textAttachment = ErrorAttachmentLog.attachmentWithText(textContent, 'hello.txt');
            const binaryAttachment = ErrorAttachmentLog.attachmentWithBinary(binaryContent, 'logo.png', 'image/png');
            return [textAttachment, binaryAttachment];
        })();
    }

    // Other callbacks must also be defined at the same time if used.
    // Default values are used if a method with return parameter isn't defined.
});

注意

若要使用該功能,您必須為當機服務正確設定應用程式。

這項功能取決於 JavaScript 中的處理損毀

注意

大小限制目前在 Android 上為 1.4 MB,在 iOS 上為 7 MB。 嘗試傳送較大的附件將會觸發錯誤。

已處理的錯誤

App Center 也可讓您透過方法使用已處理的例外狀況 trackError 來追蹤錯誤。 應用程式可以選擇性地將屬性或/和附件附加至已處理的錯誤報告,以提供進一步的內容。

try {
    // Throw error.
} catch (error) {

    // Prepare properties.
    const properties = { 'Category' : 'Music', 'Wifi' : 'On' };

    // Prepare attachments.
    const textAttachment = ErrorAttachmentLog.attachmentWithText('Hello text attachment!', 'hello.txt');
    const attachments = [textAttachment];

    // Create an exception model from error.
    const exceptionModel1 = ExceptionModel.createFromError(error);

    // ..or generate with your own error data.
    const exceptionModel2 = ExceptionModel.createFromTypeAndMessage("type", "message", "stacktrace");

    // Track error with custom data.
    Crashes.trackError(exceptionModel1, properties, attachments);
    Crashes.trackError(exceptionModel1, properties, nil);
    Crashes.trackError(exceptionModel2, nil, attachments);
    Crashes.trackError(exceptionModel2, nil, nil);
}

斷板

App Center 支援在 React Native 應用程式中從 Android NDK 損毀的斷板。

請遵循上述一般設定步驟,並在覆 MainActivity.javaOnCreate 中新增迷你傾印組態,並在您的原生程式代碼中呼叫以設定 Breakpad 組態。

範例:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Crashes.getMinidumpDirectory().thenAccept(new AppCenterConsumer<String>() {
      @Override
      public void accept(String path) {
        // Path is null when Crashes is disabled.
        if (path != null) {
          // links to NDK
          setupBreakpadListener(path);
        }
      }
    });
  }

在運行時間啟用或停用 App Center 當機

您可以在執行時間啟用和停用 App Center 當機。 如果您停用此功能,SDK 將不會對應用程式執行任何損毀報告。

await Crashes.setEnabled(false);

若要再次啟用App Center當機,請使用相同的API,但傳遞 true 做為參數。

await Crashes.setEnabled(true);

狀態會保存在應用程式啟動的裝置記憶體中。

檢查 App Center 當機是否已啟用

您也可以檢查 App Center 當機是否已啟用:

const enabled = await Crashes.isEnabled();