How can I create a Map (it that's the best way) of...
# getting-started
p
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
Maybe I don't understand completely, but:
Copy code
val codes = mapOf(
    400 -> OrganizationNotFound,
    500 -> CustomException(someData)
);
?
p
Yes, but what do I put in the generic method?
j
Maybe something like:
Copy code
fun <T : Exception> apiCallWithStatusCode(
    codes: HashMap<Int, T>,
    apiCall : suspend () -> Response<HashMap<Int, T>>
) {
    ...
}
m
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
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