简体   繁体   English

处理 AWS Amplify onError 回调异常

[英]Handling AWS Amplify onError Callback Exceptions

I'm having trouble understanding how to handle the onError callbacks from Amplify functions in Android Java.我无法理解如何处理来自 Android Java 中 Amplify 函数的 onError 回调。 For instance, below is an Amplify call to sign up a user.例如,下面是一个用于注册用户的 Amplify 调用。 The function works great and does what it is supposed to do, however, i'm unable to figure out how to handle the different types of onError callbacks that can be thrown with this function, especially since it is formated with Lambda functions. function 工作得很好,可以做它应该做的事情,但是,我无法弄清楚如何处理这个 function 可以抛出的不同类型的 onError 回调,特别是因为它是用 Z04A1BBDA93C5B05BCADZ52 函数格式化的。

For instance, if the user is already signed up, the "error" callback becomes a "UsernameExistsException", but I can't figure out how to filter for that exception and handle it.例如,如果用户已经注册,“错误”回调将变成“用户名ExistsException”,但我不知道如何过滤该异常并处理它。 Ultimately, I would like to be able to handle this specific exception to produce an AlertDialog which tells the user "this account already exists" in this example.最终,我希望能够处理这个特定的异常以生成一个 AlertDialog,在这个例子中告诉用户“这个帐户已经存在”。

There are alot of other similar functions that are structured the same way where I would like to handle other types of errors.还有很多其他类似的功能,它们的结构与我想处理其他类型的错误的方式相同。

Any help is very appreciated.非常感谢任何帮助。 For reference on how these functions are used, check out the Amplify documentation and tutorials here .有关如何使用这些函数的参考,请在此处查看 Amplify 文档和教程。

SOLVED UPDATE 1/23/21: I posted an answer below using @Jameson's answer已解决更新 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); 
            }
    );

As you note, most of Amplify Android's methods are asynchronous , and emit either a result or error in one of two callbacks .正如您所注意到的,Amplify Android 的大多数方法都是异步的,并在两个回调之一中发出结果或错误。 The callback interfaces are "simple functional interface," and so may be simplified with lambda expression syntax.回调接口是“简单功能接口”,因此可以使用 lambda 表达式语法进行简化。

In Java, you could look for the UsernameExistsException error like this:在 Java 中,您可以像这样查找UsernameExistsException错误:

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

with:和:

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();
}

Similar with Kotlin, except you can use the when construct:与 Kotlin 类似,除了可以使用when构造:

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

Thanks to @Jameson for providing some insights.感谢@Jameson 提供了一些见解。 Here is the solution I ended up using to handle errors from Amplify.这是我最终用来处理 Amplify 错误的解决方案。

Couple things to note: Due to the Amplify libraries using some old Java libraries and some new code for error handling, I wasn't able to cast the errors appropriately like in @Jameson's answer.需要注意的几件事:由于 Amplify 库使用了一些旧的 Java 库和一些用于错误处理的新代码,我无法像@Jameson 的回答那样正确地转换错误。 Something about the way the Amplify library is set up in AuthExceptions dis-allowed me to cast the root error that was being thrown.在 AuthExceptions 中设置 Amplify 库的方式不允许我转换被抛出的根错误。 The only way I was able to identify the errors correctly was by using a string.contains function to scan the string that the Amplify function outputs during an error.我能够正确识别错误的唯一方法是使用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. 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. Otherwise a looper error is thrown.否则会抛出一个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