I want to display different errors to the user when they are logging in through AWS Amplify using Kotlin. This is what I have set up as my last parameter of Amplify.Auth.signIn()
:
{ error -> inputEmail.error = "Check if the e-mail is valid" inputPassword.error = "Check if the password is valid" })
“error” is a “Throwable?” which I wanted to cast to various AWS exceptions and check whether the cast was a success. Yet all of the AWS Amplify exceptions are based on the Java version of “Throwable”. Is there a way to make these casts work or is there an alternative way to identify error types in Kotlin?
Advertisement
Answer
The last argument in the signIn(...)
method is of type Consumer<AuthException>
. This is a function that accepts an AuthException
, and does something with it. So, you shouldn’t need to downcast the input.
There are a few types exception that extend AuthException
.
As in this answer, I suggest is to exhaust those types using a when
construct. Paraphrasing:
when (error) { is SessionUnavailableOfflineException -> doSomething() is InvalidAccountTypeException -> doSomethingElse() // etc. }
You can also check for errors in the active auth session with 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()) } )