我正在使用 AWS SDK 设置 Cognito(无放大)。 我注意到,当发生某些情况时,我的 try/catch
Exception
类型无法捕获 AWS 特定的 Exception
类型。
如何在一个 catch 块中雄辩地捕获 AWS 的所有异常?
下面是一些示例代码,理想情况下我想在一个块中捕获所有 Cognito 特定异常:
AuthenticationScreenState.REGISTER_VALIDATION -> {
try {
// confirm account request
confirmSignUp()
setScreenVisibility(false)
delay(300)
screenStateTo(AuthenticationScreenState.VALIDATION_COMPLETE)
}catch(e: UsernameExistsException){
setAuthenticationErrorMessage(e.message)
}
catch(e: NotAuthorizedException){
setAuthenticationErrorMessage(e.message)
}
catch(e: ExpiredCodeException){
setAuthenticationErrorMessage(e.message)
}
catch(e: Exception){
Log.d("Exception", e.message.toString())
setAuthenticationErrorMessage(e.message)
}
}
现在,看看他们的模型,他们有多个继承自
CognitoIdentityProviderException(builder.message)
的异常情况。我在下面粘贴了异常片段的示例。
//Exception snippet from aws.sdk.kotlin.services.cognitoIdentityprovider -> model
public class ExpiredCodeException private constructor(builder: Builder) : CognitoIdentityProviderException(builder.message) {
init {
sdkErrorMetadata.attributes[ServiceErrorMetadata.ErrorType] = ErrorType.Client
}
public companion object {
public operator fun invoke(block: Builder.() -> kotlin.Unit): aws.sdk.kotlin.services.cognitoidentityprovider.model.ExpiredCodeException = Builder().apply(block).build()
}
override fun toString(): kotlin.String = buildString {
append("ExpiredCodeException(")
append("message=$message")
append(")")
}
override fun hashCode(): kotlin.Int {
var result = message?.hashCode() ?: 0
return result
}
override fun equals(other: kotlin.Any?): kotlin.Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ExpiredCodeException
if (message != other.message) return false
return true
}
public inline fun copy(block: Builder.() -> kotlin.Unit = {}): aws.sdk.kotlin.services.cognitoidentityprovider.model.ExpiredCodeException = Builder(this).apply(block).build()
@SdkDsl
public class Builder {
/**
* The message returned when the expired code exception is thrown.
*/
public var message: kotlin.String? = null
@PublishedApi
internal constructor()
@PublishedApi
internal constructor(x: aws.sdk.kotlin.services.cognitoidentityprovider.model.ExpiredCodeException) : this() {
this.message = x.message
}
@PublishedApi
internal fun build(): aws.sdk.kotlin.services.cognitoidentityprovider.model.ExpiredCodeException = ExpiredCodeException(this)
internal fun correctErrors(): Builder {
return this
}
}
}
我尝试添加此代码片段,但它似乎无法推断所有子异常的父类型。
catch(e: CognitoIdentityProviderException){
Log.d("CognitoProviderException", e.message)
setAuthenticationErrorMessage(e.message)
}
找到了一种方法来做到这一点:将继续测试,但我使用了以下代码,它似乎有效。
}catch (e: CognitoIdentityProviderException) {
val exceptionName = e::class.simpleName
Log.d("Exception", exceptionName.toString() + e.message)
setAuthenticationErrorMessage("$exceptionName: ${e.message}")
}