-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
SentryOkHttpInterceptor.kt
56 lines (47 loc) · 1.68 KB
/
SentryOkHttpInterceptor.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io.sentry.android.okhttp
import io.sentry.Breadcrumb
import io.sentry.HubAdapter
import io.sentry.IHub
import io.sentry.SpanStatus
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Response
class SentryOkHttpInterceptor(
private val hub: IHub = HubAdapter.getInstance()
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val url = request.url.toString()
val method = request.method
// read transaction from the bound scope
val span = hub.span?.startChild("http.client", "$method $url")
var response: Response? = null
var code: Int? = null
try {
span?.toSentryTrace()?.let {
request = request.newBuilder().addHeader(it.name, it.value).build()
}
response = chain.proceed(request)
code = response.code
return response
} catch (e: IOException) {
span?.throwable = e
throw e
} finally {
span?.finish(SpanStatus.fromHttpStatusCode(code, SpanStatus.INTERNAL_ERROR))
val breadcrumb = Breadcrumb.http(request.url.toString(), request.method, code)
request.body?.contentLength().ifHasValidLength {
breadcrumb.setData("requestBodySize", it)
}
response?.body?.contentLength().ifHasValidLength {
breadcrumb.setData("responseBodySize", it)
}
hub.addBreadcrumb(breadcrumb)
}
}
private fun Long?.ifHasValidLength(fn: (Long) -> Unit) {
if (this != null && this != -1L) {
fn.invoke(this)
}
}
}