【问题标题】:How to identify authentification error type in AWS Amplify using Kotlin?如何使用 Kotlin 识别 AWS Amplify 中的身份验证错误类型?
【发布时间】:2020-08-03 23:02:43
【问题描述】:

当用户使用 Kotlin 通过 AWS Amplify 登录时,我想向他们显示不同的错误。这是我设置为Amplify.Auth.signIn()的最后一个参数:

{ error ->
     inputEmail.error = "Check if the e-mail is valid"
     inputPassword.error = "Check if the password is valid"
})

“error”是一个“Throwable?”我想将其转换为各种 AWS 异常并检查转换是否成功。然而,所有 AWS Amplify 异常都基于 Java 版本的“Throwable”。有没有办法让这些强制转换起作用,或者有没有其他方法可以识别 Kotlin 中的错误类型?

【问题讨论】:

    标签: java amazon-web-services kotlin aws-amplify


    【解决方案1】:

    the signIn(...) 方法中的最后一个参数是Consumer<AuthException> 类型。这是一个接受AuthException 并对其进行处理的函数。因此,您不需要downcast 输入。

    a few types exception that extend AuthException

    this answer 一样,我建议使用when 构造来耗尽这些类型。释义:

    when (error) {
        is SessionUnavailableOfflineException -> doSomething()
        is InvalidAccountTypeException -> doSomethingElse()
        // etc.
    }
    

    您还可以使用fetchAuthSession(...) 检查活动身份验证会话中的错误:

    Amplify.Auth.fetchAuthSession(
        { result ->
            val cognitoAuthSession = result as AWSCognitoAuthSession
            if (AuthSessionResult.Type.FAILURE == cognitoAuthSession.identityId.type) {
                // do stuff
            }
        },
        { error -> Log.e("AuthQuickStart", error.toString()) }
    )
    

    【讨论】:

    • 这是一种更优雅的检查其类型的方法,是的,谢谢。但是假设我想检查“UserNotConfirmedException”,我只在消息中被告知,但“错误”对它是不可转换的。 Amplify.Auth.fetchAuthSession() 是否可以检查此类错误?
    • 嘿@KapitaiN - 您是对的,目前我们不会对您要识别的错误进行分类,例如 UserNotConfirmed、用户名不存在或密码错误。这是我们意识到并在我们的积压工作中需要解决的差距。
    • @DavidDaudelin 好的,感谢您的帮助!那我会想办法的。
    猜你喜欢
    • 2021-03-17
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2020-01-01
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多