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

How to get the URL endpoint and the GET/POST method when an Exception occurs? #4174

Closed
vstung89 opened this issue Jun 20, 2024 · 2 comments
Closed

Comments

@vstung89
Copy link

Hello everyone, I need help with an issue.

I use a suspend function to call the API as shown in the code below. How can I get the URL endpoint and the GET/POST method when an Exception occurs?

suspend fun <T : BaseResponse> safeCallApi(
	api: suspend () -> Response<T>
): Result<T> {
	return try {
		val response = api()
		if (response.isSuccessful) {
			val body = response.body()
			if (body != null) {
				Result.success(body)
			} else {
				Result.failure(BodyNullException())
			}
		} else {
			Result.failure(ServerException())
		}
	} catch (e: Exception) {
		// I want to obtain the information about the URL endpoint and the GET/POST method there.
		Result.failure(UnknownException(e))
	}
}
@angusholder
Copy link
Contributor

You'll need to change your API method from

suspend fun myApiMethod(): Response<T>

to

fun myApiMethod(): Call<T>

then change your code above to

val call: Call<T> = api()
try {
    val response: Response<T> = call.awaitResponse()
    ..
} catch (e: Exception) {
    call.request().method // use me
    call.request().url // use me
    Result.failure(UnknownException(e))
}

@JakeWharton
Copy link
Member

Yeah there's basically no way to do this when using a "raw" suspend function because we become at the mercy of underlying libraries and how they throw exceptions. An HttpException includes a Response from which you can get the Request, but IOException subtypes won't have that. The only way to retrieve that information is as posted above, where you create the Call explicitly and perform suspended-execution separately.

@JakeWharton JakeWharton closed this as not planned Won't fix, can't repro, duplicate, stale Jul 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants