Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error handling of coroutines API #373

Merged
merged 18 commits into from Jul 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 63 additions & 0 deletions README.md
Expand Up @@ -692,6 +692,69 @@ Fuel.request(WeatherApi.weatherFor("london")).responseJson { request, response,
}
```

### Coroutines Support

Coroutines module provides extension functions to wrap a response inside a coroutine and handle its result. The coroutines-based API provides equivalent methods to the standard API (e.g: `responseString()` in coroutines is `awaitString()`).

```kotlin
runBlocking {
val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitString()

result.fold({ data ->
println(data) // "{"origin":"127.0.0.1"}"
}, { error ->
println("An error of type ${error.exception} happened: ${error.message}")
})
}
```

It also provides useful methods to handle the `Result` value directly. The difference is that they throw exception instead of returning it wrapped a `FuelError` instance.

```kotlin
runBlocking {
try {
println(Fuel.get("https://httpbin.org/ip").awaitStringResult()) // "{"origin":"127.0.0.1"}"
} catch(exception: HttpException) {
println("A network request exception was thrown: ${exception.message}")
}
}
```

Handling objects other than `String` (`awaitString()`) or `ByteArray` (`awaitResponse()`) can be done using `awaitSafelyObjectResult` or `awaitObjectResult`.

```kotlin
data class Ip(val origin: String)

object IpDeserializer : ResponseDeserializable<Ip> {
override fun deserialize(content: String) =
jacksonObjectMapper().readValue<Ip>(content)
}
```

```kotlin
runBlocking {
Fuel.get("https://httpbin.org/ip").awaitSafelyObjectResult(IpDeserializer)
.fold({ data ->
println(data.origin) // 127.0.0.1
}, { error ->
println("An error of type ${error.exception} happened: ${error.message}")
})
}
```

```kotlin
runBlocking {
try {
val data = Fuel.get("https://httpbin.org/ip").awaitObjectResult(IpDeserializer)
println(data.origin) // 127.0.0.1
} catch (exception: HttpException) {
println("A network request exception was thrown: ${exception.message}")
} catch (exception: JsonMappingException) {
println("A serialization/deserialization exception was thrown: ${exception.message}")
}
}
```

## Other libraries
If you like Fuel, you might also like other libraries of mine;
* [Result](https://github.com/kittinunf/Result) - The modelling for success/failure of operations in Kotlin
Expand Down
@@ -1,7 +1,13 @@
import com.github.kittinunf.fuel.core.*
import com.github.kittinunf.fuel.core.Deserializable
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Request.Companion.byteArrayDeserializer
import com.github.kittinunf.fuel.core.Request.Companion.stringDeserializer
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.kittinunf.fuel.core.response
import com.github.kittinunf.result.Result
import com.github.kittinunf.result.mapError
import kotlinx.coroutines.experimental.suspendCancellableCoroutine
import java.nio.charset.Charset

Expand All @@ -10,32 +16,37 @@ private suspend fun <T : Any, U : Deserializable<T>> Request.await(
): Triple<Request, Response, Result<T, FuelError>> =
suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() }
response(deserializable) { request: Request, response: Response, result: Result<T, FuelError> ->
result.fold({
continuation.resume(Triple(request, response, result))
}, {
continuation.resumeWithException(it.exception)
})
}
continuation.resume(response(deserializable))
}


suspend fun Request.awaitResponse(): Triple<Request, Response, Result<ByteArray, FuelError>> =
await(byteArrayDeserializer())

suspend fun Request.awaitString(
charset: Charset = Charsets.UTF_8
): Triple<Request, Response, Result<String, FuelError>> = await(stringDeserializer(charset))

@Deprecated(
replaceWith = ReplaceWith(
expression = ".awaitSafelyObjectResult"),
level = DeprecationLevel.WARNING,
message = "This function cannot handle exceptions properly which causes API inconsistency.")
@Throws
suspend fun <U : Any> Request.awaitObject(
deserializable: ResponseDeserializable<U>
): Triple<Request, Response, Result<U, FuelError>> = await(deserializable)

suspend fun Request.awaitResponseResult(): ByteArray = awaitResponse().third.get()
@Throws
suspend fun Request.awaitResponseResult(): ByteArray = awaitResponse().third
.mapError { throw it.exception }
.get()

@Throws
suspend fun Request.awaitStringResult(
charset: Charset = Charsets.UTF_8
): String = awaitString(charset).third.get()
): String = awaitString(charset).third
.mapError { throw it.exception }
.get()

/**
* This function will throw the an exception if an error is thrown either at the HTTP level
Expand All @@ -45,9 +56,12 @@ suspend fun Request.awaitStringResult(
*
* @return Result object
* */
@Throws
suspend fun <U : Any> Request.awaitObjectResult(
deserializable: ResponseDeserializable<U>
): U = await(deserializable).third.get()
): U = await(deserializable).third
.mapError { throw it.exception }
.get()

/**
* This function catches both server errors and Deserialization Errors
Expand All @@ -67,4 +81,3 @@ suspend fun <U : Any> Request.awaitSafelyObjectResult(
}
Result.Failure(fuelError)
}