1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.credentials.exceptions.publickeycredential
18 
19 import androidx.annotation.RestrictTo
20 import androidx.credentials.CredentialManager
21 import androidx.credentials.exceptions.CreateCredentialCustomException
22 import androidx.credentials.exceptions.CreateCredentialException
23 import androidx.credentials.internal.FrameworkClassParsingException
24 
25 /**
26  * A subclass of CreateCredentialException for unique exceptions thrown specific only to
27  * PublicKeyCredentials. See [CredentialManager] for more details on how Credentials work for
28  * Credential Manager flows.
29  *
30  * @throws NullPointerException if [type] is null
31  * @throws IllegalArgumentException if [type] is empty
32  */
33 open class CreatePublicKeyCredentialException
34 @JvmOverloads
35 internal constructor(
36     @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) override val type: String,
37     errorMessage: CharSequence? = null
38 ) : CreateCredentialException(type, errorMessage) {
39     init {
<lambda>null40         require(type.isNotEmpty()) { "type must not be empty" }
41     }
42 
43     internal companion object {
44         @JvmStatic
45         @RestrictTo(RestrictTo.Scope.LIBRARY) // used from java tests
createFromnull46         fun createFrom(type: String, msg: String?): CreateCredentialException {
47             return try {
48                 with(type) {
49                     when {
50                         contains(
51                             CreatePublicKeyCredentialDomException
52                                 .TYPE_CREATE_PUBLIC_KEY_CREDENTIAL_DOM_EXCEPTION
53                         ) -> CreatePublicKeyCredentialDomException.createFrom(type, msg)
54                         else -> {
55                             throw FrameworkClassParsingException()
56                         }
57                     }
58                 }
59             } catch (t: FrameworkClassParsingException) {
60                 // Parsing failed but don't crash the process. Instead just output a response
61                 // with the raw framework values.
62                 CreateCredentialCustomException(type, msg)
63             }
64         }
65     }
66 }
67