https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pablo

01/02/2022, 12:59 PM
How can I create a Map (it that's the best way) of having something for instance : 400 to CustomExceptionFor400 500 to CustomExceptionFor500 The first param is an Int and it's a HttpStatusCode, and the value is something like this
Copy code
sealed class OrganizationExceptions : Exception() {
    object OrganizationNotFound : OrganizationExceptions()
    object ListNotAvailable : OrganizationExceptions()
}
This is an example, but it won't be always "OrganizationExceptions" I'm creating a method generic, also I don't know if it's better to create a sealed class or create
Copy code
class OrganizationNotFoundException : Throwable() //or Exception()
class ListNotAvailable : Throwable() //or Exception()
Any recomendations? the method signature is :
fun apiCallWithStatusCode(codes : HashMap<Int, Throwable>, apiCall : suspend () -> Response<T>,){...}
a

Arjan van Wieringen

01/02/2022, 6:00 PM
Maybe I don't understand completely, but:
Copy code
val codes = mapOf(
    400 -> OrganizationNotFound,
    500 -> CustomException(someData)
);
?
p

Pablo

01/02/2022, 6:42 PM
Yes, but what do I put in the generic method?
j

James Whitehead

01/02/2022, 8:26 PM
Maybe something like:
Copy code
fun <T : Exception> apiCallWithStatusCode(
    codes: HashMap<Int, T>,
    apiCall : suspend () -> Response<HashMap<Int, T>>
) {
    ...
}
m

Michael de Kaste

01/03/2022, 12:32 PM
If you make the
Throwable
of your method signature to an
out Throwable
, maybe something like this?
Copy code
interface ExceptionCodeMap {
    val codes: Map<Int, Throwable>
}

sealed class OrganizationExceptions : Exception(){
    object OrganizationNotFound : OrganizationExceptions()
    object ListNotAvailable : OrganizationExceptions()

    companion object : ExceptionCodeMap {
        override val codes = mapOf(
            400 to OrganizationNotFound,
            500 to ListNotAvailable
        )
    }
}

fun main(){
    apiCallWithStatusCode(OrganizationExceptions.codes){
        ...
    }
}
Also, maybe dont specify map implementation in the api, otherwise, instead of
mapOf
create a custom HashMap
if you make the signature like so:
fun <T : Throwable> apiCallWithStatusCode(codes: Map<Int, T>, apiCall : suspend () -> Response<T>,){...}
you have access to the correct type T within the function
p

Pablo

01/04/2022, 7:14 AM
If I have this
Copy code
class MyCustomException : Throwable
How can I return this MyCustomException in a method that gets a generic Throwable?
@James Whitehead, @Michael de Kaste, @Arjan van Wieringen thanks for replying, I've created a StackOverflow question to make it clear, let me know if you can help me out! https://stackoverflow.com/questions/70575219/how-to-add-generic-throwable-on-a-method-signature
👍 1
2 Views