tryFetch

suspend fun <T> WindowOrWorkerGlobalScope.tryFetch(method: HttpMethod, resource: String, body: RequestBody? = null, headers: Map<String, Any>? = FetchDefaults.Headers, redirect: RequestRedirect? = FetchDefaults.Redirect, logOnError: Boolean = false, abortController: AbortController? = null, transform: suspend Response.() -> T): T?(source)

A convenience version of fetch that safely converts the initial request into some target object of type T.

Essentially, if an exception is thrown at any point between making the request and converting it into its final form, it will be swallowed and null will be returned. If logOnError is set to true, logs about what went wrong will be added to the console.

You are expected to pass conversion logic into the transform callback. In other words, you should prefer

tryFetch(/*...*/) { convert() }

over

tryFetch(/*...*/)?.convert()

as the former will handle catching any exceptions around the conversion process as well as report if (if logOnError is true).

If you don't care about converting the response to some other format, you should use the tryFetch method that returns a Response? instead.


suspend fun WindowOrWorkerGlobalScope.tryFetch(method: HttpMethod, resource: String, body: RequestBody? = null, headers: Map<String, Any>? = FetchDefaults.Headers, redirect: RequestRedirect? = FetchDefaults.Redirect, logOnError: Boolean = false, abortController: AbortController? = null): Response?(source)

A convenience version of fetch that returns null instead of throwing if the request fails.

Essentially, if an exception is thrown at any point between sending the request and receiving the response, it will be swallowed and null will be returned. If logOnError is set to true, logs about what went wrong will be added to the console.

If you plan to do additional operations on the response and would also like to have logging / exception protection for them, consider using the other tryFetch call which lets you pass in a transform callback. In other words, you should prefer

tryFetch(/*...*/) { convert() }

over

tryFetch(/*...*/)?.convert()