Hey Guys, I am working in ktor api response. I wan...
# codereview
v
Hey Guys, I am working in ktor api response. I want to handle api response. So i read from some medium post. I tried some code. Can you suggest me if there is any better approach then this?
Copy code
package com.example.kotlinmultiplatformsharedmodule
 
 sealed class ApiResponse<out T : Any> {
 
     data class Success<out T : Any>(
         val data: T?
     ) : ApiResponse<T>()
 
     data class Error(
         val exception: Throwable? = null,
         val responseCode: Int = -1,
         val errorResponse: ErrorResponse? = null
     ) : ApiResponse<Nothing>()
 
     fun handleResult(onSuccess: ((responseData: T?) -> Unit)?,onError: ((error: Error) -> Unit)?) {
         when (this) {
             is Success -> {
                 onSuccess?.invoke(this.data)
             }
             is Error -> {
                 onError?.invoke(this)
             }
         }
     }
 }
 
 data class ErrorResponse(
     val errorCode: Int,
     val errorMessage: String
 )
r
Hey, it seems like you want to create an instance of ApiResponse for every request's response. The most common return type, however, is going to be Success which is just a wrapper around "data". So in this case I'd make use of the StatusPage plugin and throw an exception that contains further information about the error. https://ktor.io/docs/status-pages.html#exceptions
For my part, I created an ApiError class that extends RuntimeException together with some nice helper functions.