簡體   English   中英

處理 AWS Amplify onError 回調異常

[英]Handling AWS Amplify onError Callback Exceptions

我無法理解如何處理來自 Android Java 中 Amplify 函數的 onError 回調。 例如,下面是一個用於注冊用戶的 Amplify 調用。 function 工作得很好,可以做它應該做的事情,但是,我無法弄清楚如何處理這個 function 可以拋出的不同類型的 onError 回調,特別是因為它是用 Z04A1BBDA93C5B05BCADZ52 函數格式化的。

例如,如果用戶已經注冊,“錯誤”回調將變成“用戶名ExistsException”,但我不知道如何過濾該異常並處理它。 最終,我希望能夠處理這個特定的異常以生成一個 AlertDialog,在這個例子中告訴用戶“這個帳戶已經存在”。

還有很多其他類似的功能,它們的結構與我想處理其他類型的錯誤的方式相同。

非常感謝任何幫助。 有關如何使用這些函數的參考,請在此處查看 Amplify 文檔和教程。

已解決更新 21 年 1月 23 日:我使用@Jameson的回答在下面發布了一個答案

Amplify.Auth.signUp(
            user_email,
            user_password,
            AuthSignUpOptions.builder().userAttributes(attributes).build(),
            result -> {
                Log.i("AuthQuickStart", "Result: " + result.toString());
                Intent intent = new Intent(SignUpActivity.this, SignUpAuthActivity.class);
                Bundle bun = new Bundle();
                bun.putSerializable("user", user);
                intent.putExtras(bun);
                startActivity(intent);
                finish();
            },

            error -> {
                //in the example, the Error becomes the UsernameExistsException callback
                Log.e("AuthQuickStart", "Sign up failed", error); 
            }
    );

正如您所注意到的,Amplify Android 的大多數方法都是異步的,並在兩個回調之一中發出結果或錯誤。 回調接口是“簡單功能接口”,因此可以使用 lambda 表達式語法進行簡化。

在 Java 中,您可以像這樣查找UsernameExistsException錯誤:

AuthSignUpOptions options =
    AuthSignUpOptions.builder()
        .userAttributes(attributes)
        .build();
Amplify.Auth.signUp(username, password, options,
    result -> { /* handle result ... */ },
    error -> {
        if (error instanceof UsernameExistsException) {
            showAlreadyExistsDialog();
        }
    }
);

和:

private void showAlreadyExistsDialog() {
    new AlertDialog.Builder(context)
        .setTitle("User already exists!")
        .setMessage("Tried to sign-up an already-existing user.")
        .setPositiveButton(android.R.string.yes, (dialog, which) -> {
            // on click...
        })
        .setNegativeButton(android.R.string.no, null)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .show();
}

與 Kotlin 類似,除了可以使用when構造:

val options = AuthSignUpOptions.builder()
    .userAttributes(attributes)
    .build()
Amplify.Auth.signUp(username, password, options,
    { /* result handling ... */ },
    { error ->
        when (error) {
            is UsernameExistsException -> 
                showAlreadyExistsDialog()
        }
    }
)

感謝@Jameson 提供了一些見解。 這是我最終用來處理 Amplify 錯誤的解決方案。

需要注意的幾件事:由於 Amplify 庫使用了一些舊的 Java 庫和一些用於錯誤處理的新代碼,我無法像@Jameson 的回答那樣正確地轉換錯誤。 在 AuthExceptions 中設置 Amplify 庫的方式不允許我轉換被拋出的根錯誤。 我能夠正確識別錯誤的唯一方法是使用string.contains function 來掃描 Amplify function 在錯誤期間輸出的字符串。

Also, due to the lambda function format, you have to run a thread inside the lambda function to be able to interact with the UI elements. 否則會拋出一個looper錯誤。

Amplify.Auth.signIn(
            user_email,
            user_pass,
            result -> {
                Log.i("AmplifyAuth", result.isSignInComplete() ? "Sign in succeeded" : "Sign in not complete");
                startActivity(new Intent(LoginActivity.this, MainDashActivity.class));
                finish();
            },
            error -> {
                Log.e("AmplifyAuth", error.toString());
                //Handles incorrect username/password combo
                if (error.getCause().toString().contains("Incorrect username or password") ) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            incorrectLoginDialog.show();
                        }
                    });
                    return;
                }

                //Handles too many login attempts
                if (error.getCause().toString().contains("Password attempts exceeded") ) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tooManyAttemptsDialog.show();
                        }
                    });
                    return;
                }

                //Handles when the email user does not exist in the user pool
                if (error.getCause().toString().contains("User does not exist") ) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            doesNotExistDialog.show();
                        }
                    });
                    return;
                }
            }
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM