Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Last active March 10, 2022 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/0c14f3e7a014d4578727662ef4f52fd9 to your computer and use it in GitHub Desktop.
Save rommansabbir/0c14f3e7a014d4578727662ef4f52fd9 to your computer and use it in GitHub Desktop.
A generic API to execute a given body and return an object [T] type. If exception occur return null else the object [T].
class GenericBodyExecutor {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(executeBodyOrReturnNull<Int> { GenericData("0").data.toInt() }) // Result -> 0
println(executeBodyOrReturnNull<Int> { GenericData("Hello").data.toInt() }) // Result -> null
}
}
}
data class GenericData(val data: String)
/**
* A generic API to execute a given body and return an object [T] type.
* If exception occur return null else the object [T].
*
* @param T Object type.
* @param body Code block to be executed under try catch and should return [T].
*
* @return [T] object can be nullable.
*/
inline fun <T> executeBodyOrReturnNull(crossinline body: () -> T): T? {
return try {
body.invoke()
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
suspend inline fun <T> executeBodyOrReturnNullIOScope(crossinline body: CoroutineScope.() -> T): T? {
return withContext(Dispatchers.IO) {
try {
body.invoke(this)
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
inline fun <T> executeBodyOrReturnNull(
crossinline body: () -> T,
crossinline errorBody: (Exception) -> Unit = {}
): T? {
return try {
body.invoke()
} catch (e: Exception) {
errorBody.invoke(e)
null
}
}
suspend inline fun <T> executeBodyOrReturnNullIOScope(
crossinline body: CoroutineScope.() -> T,
crossinline errorBody: (Exception) -> Unit = {}
): T? {
return withContext(Dispatchers.IO) {
try {
body.invoke(this)
} catch (e: Exception) {
errorBody.invoke(e)
null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment