// Copyright © 2022 Olo Inc. All rights reserved. // This software is made available under the Olo Pay SDK License (See LICENSE.md file) package com.olopaysdkreactnative.extensions import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.olo.olopay.data.CardErrorType import com.olo.olopay.exceptions.ApiConnectionException import com.olo.olopay.exceptions.ApiException import com.olo.olopay.exceptions.CardException import com.olo.olopay.exceptions.InvalidRequestException import com.olo.olopay.exceptions.OloPayException import com.olo.olopay.exceptions.RateLimitException import com.olopaysdkreactnative.data.DataKeys import com.olopaysdkreactnative.data.ErrorCodes fun OloPayException.toResultErrorMap(): WritableMap { val map = Arguments.createMap() map.putString(DataKeys.MessageKey, getErrorMessage("Unexpected error occurred")) map.putString(DataKeys.CodeKey, getErrorCode()) return map } fun OloPayException.getErrorMessage(defaultMessage: String): String { return message.orEmpty().ifEmpty { defaultMessage } } fun OloPayException.getErrorCode(): String { val cardException = this as? CardException if (cardException != null) { return getErrorCode(cardException.type) } if (this is ApiException) return ErrorCodes.ApiError if (this is InvalidRequestException) return ErrorCodes.InvalidRequest if (this is ApiConnectionException) return ErrorCodes.ConnectionError if (this is RateLimitException) return ErrorCodes.ApiError return ErrorCodes.GeneralError } private fun getErrorCode(cardErrorType: CardErrorType): String { return when (cardErrorType) { CardErrorType.InvalidNumber -> ErrorCodes.InvalidNumber CardErrorType.InvalidExpMonth -> ErrorCodes.InvalidExpiration CardErrorType.InvalidExpYear -> ErrorCodes.InvalidExpiration CardErrorType.InvalidCVV -> ErrorCodes.InvalidCvv CardErrorType.InvalidZip -> ErrorCodes.InvalidPostalCode CardErrorType.ExpiredCard -> ErrorCodes.ExpiredCard CardErrorType.CardDeclined -> ErrorCodes.CardDeclined CardErrorType.ProcessingError -> ErrorCodes.ProcessingError CardErrorType.UnknownCardError -> ErrorCodes.UnknownCard } }