How to use wrap method of com.github.kittinunf.fuel.core.FuelError class

Best Fuel code snippet using com.github.kittinunf.fuel.core.FuelError.wrap

Deserializable.kt

Source:Deserializable.kt Github

copy

Full Screen

...37 ?: deserialize(stream.reader())38 ?: reserialize(response, stream).let {39 deserialize(response.data)40 ?: deserialize(String(response.data))41 ?: throw FuelError.wrap(IllegalStateException(42 "One of deserialize(ByteArray) or deserialize(InputStream) or deserialize(Reader) or " +43 "deserialize(String) must be implemented"44 ))45 }46 }47 }48 private fun reserialize(response: Response, stream: InputStream): Response {49 val length = response.body.length50 response.body = DefaultBody.from({ stream }, length?.let { l -> { l } })51 return response52 }53 /**54 * Deserialize into [T] from an [InputStream]55 *56 * @param inputStream [InputStream] source bytes57 * @return [T] deserialized instance of [T] or null when not applied58 */59 fun deserialize(inputStream: InputStream): T? = null60 /**61 * Deserialize into [T] from a [Reader]62 *63 * @param reader [Reader] source bytes64 * @return [T] deserialized instance of [T] or null when not applied65 */66 fun deserialize(reader: Reader): T? = null67 /**68 * Deserialize into [T] from a [ByteArray]69 *70 * @note it is more efficient to implement the [InputStream] variant.71 *72 * @param bytes [ByteArray] source bytes73 * @return [T] deserialized instance of [T] or null when not applied74 */75 fun deserialize(bytes: ByteArray): T? = null76 /**77 * Deserialize into [T] from a [String]78 *79 * @note it is more efficient to implement the [Reader] variant.80 *81 * @param content [String] source bytes82 * @return [T] deserialized instance of [T] or null when not applied83 */84 fun deserialize(content: String): T? = null85}86/**87 * Deserialize the [Response] to the [this] into a [T] using [U]88 *89 * @see ResponseResultHandler90 *91 * @param deserializable [U] the instance that performs deserialization92 * @param handler [ResponseResultHandler<T>] handler that has a [Result]93 * @return [CancellableRequest] the request that can be cancelled94 */95fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseResultHandler<T>): CancellableRequest =96 response(deserializable,97 { request, response, value -> handler(request, response, Result.Success(value)) },98 { request, response, error -> handler(request, response, Result.Failure(error)) }99 )100/**101 * Deserialize the [Response] to the [this] into a [T] using [U]102 *103 * @see ResultHandler104 *105 * @param deserializable [U] the instance that performs deserialization106 * @param handler [ResultHandler<T>] handler that has a [Result]107 * @return [CancellableRequest] the request that can be cancelled108 */109fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResultHandler<T>): CancellableRequest =110 response(deserializable,111 { _, _, value -> handler(Result.Success(value)) },112 { _, _, error -> handler(Result.Failure(error)) }113 )114/**115 * Deserialize the [Response] to the [this] into a [T] using [U]116 *117 * @see ResponseHandler118 *119 * @param deserializable [U] the instance that performs deserialization120 * @param handler [ResponseHandler<T>] handler that has dedicated paths for success and failure121 * @return [CancellableRequest] the request that can be cancelled122 */123fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseHandler<T>): CancellableRequest =124 response(deserializable,125 { request, response, value -> handler.success(request, response, value) },126 { request, response, error -> handler.failure(request, response, error) }127 )128/**129 * Deserialize the [Response] to the [this] into a [T] using [U]130 *131 * @see Handler132 *133 * @param deserializable [U] the instance that performs deserialization134 * @param handler [Handler<T>] handler that has dedicated paths for success and failure135 * @return [CancellableRequest] the request that can be cancelled136 */137fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: Handler<T>): CancellableRequest =138 response(deserializable,139 { _, _, value -> handler.success(value) },140 { _, _, error -> handler.failure(error) }141 )142/**143 * Deserialize the [Response] to the [this] into a [T] using [U]144 *145 * @note not async, use the variations with a handler instead.146 *147 * @throws Exception if there is an internal library error, not related to Network or Deserialization148 *149 * @param deserializable [U] the instance that performs deserialization150 * @return [ResponseResultOf<T>] the response result of151 */152fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {153 // First execute the network request and catch any issues154 val rawResponse = runCatching { toTask().call() }155 .onFailure { error ->156 FuelError.wrap(error, Response.error(url)).also {157 return Triple(this, it.response, Result.error(it))158 }159 }160 .getOrThrow()161 // By this time it should have a response, but deserialization might fail162 return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }163 .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }164 .getOrThrow()165}166/**167 * Ignore the response result168 *169 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]170 * to a large download and without using the result [ByteArray]171 *172 * @see [com.github.kittinunf.fuel.core.Request.response]173 *174 * @note not async, use the variations with a handler instead.175 *176 * @throws Exception if there is an internal library error, not related to Network177 */178fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)179private fun <T : Any, U : Deserializable<T>> Request.response(180 deserializable: U,181 success: (Request, Response, T) -> Unit,182 failure: (Request, Response, FuelError) -> Unit183): CancellableRequest {184 val asyncRequest = RequestTaskCallbacks(185 request = this,186 onSuccess = { response ->187 // The network succeeded but deserialization might fail188 val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }189 executionOptions.callback {190 deliverable.fold(191 { success(this, response, it) },192 { failure(this, response, FuelError.wrap(it, response).also { error ->193 Fuel.trace { "[Deserializable] unfold failure: \n\r$error" } })194 }195 )196 }197 },198 onFailure = { error, response ->199 executionOptions.callback {200 failure(this, response, error.also { error ->201 Fuel.trace { "[Deserializable] callback failure: \n\r$error" }202 })203 }204 }205 )206 return CancellableRequest.enableFor(this, future = executionOptions.submit(asyncRequest))207}208/**209 * Await [T] or throws [FuelError]210 * @return [T] the [T]211 */212@Throws(FuelError::class)213suspend fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U): T {214 val response = suspendable().await()215 return runCatching { deserializable.deserialize(response) }216 .onFailure { throw FuelError.wrap(it, response) }217 .getOrThrow()218}219/**220 * Await the task or throws [FuelError] in current coroutine context.221 *222 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]223 * to a large file without using response result224 *225 * To run method in different coroutine context, use `com.github.kittinunf.fuel.coroutines.awaitUnit` in `fuel-coroutines` module226 */227@Throws(FuelError::class)228suspend fun Request.awaitUnit(): Unit = await(EmptyDeserializer)229/**230 * Await [T] or [FuelError]231 * @return [ResponseOf<T>] the [Result] of [T]232 */233@Throws(FuelError::class)234suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponse(deserializable: U): ResponseOf<T> {235 val response = suspendable().await()236 return runCatching { Triple(this, response, deserializable.deserialize(response)) }237 .onFailure { throw FuelError.wrap(it, response) }238 .getOrThrow()239}240/**241 * Await [T] or [FuelError]242 * @return [Result<T>] the [Result] of [T]243 */244suspend fun <T : Any, U : Deserializable<T>> Request.awaitResult(deserializable: U): Result<T, FuelError> {245 val initialResult = suspendable().awaitResult()246 return serializeFor(initialResult, deserializable).map { (_, t) -> t }247}248/**249 * Await [T] or [FuelError]250 * @return [ResponseResultOf<T>] the [ResponseResultOf] of [T]251 */252suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponseResult(deserializable: U): ResponseResultOf<T> {253 val initialResult = suspendable().awaitResult()254 return serializeFor(initialResult, deserializable).let {255 Triple(this,256 it.fold({ (response, _) -> response }, { error -> error.response }),257 it.map { (_, t) -> t }258 )259 }260}261private fun <T : Any, U : Deserializable<T>> serializeFor(result: Result<Response, FuelError>, deserializable: U) =262 result.map { (it to deserializable.deserialize(it)) }263 .mapError <Pair<Response, T>, Exception, FuelError> {264 FuelError.wrap(it, result.getOrElse { Response.error() })265 }...

Full Screen

Full Screen

ObjectTest.kt

Source:ObjectTest.kt Github

copy

Full Screen

...23private object UUIDResponseDeserializer : ResponseDeserializable<UUIDResponse> {24 class NoValidFormat(m: String = "Not a UUID") : Exception(m)25 override fun deserialize(content: String): UUIDResponse {26 if (content.contains("=") || !content.contains("-")) {27 throw FuelError.wrap(NoValidFormat())28 }29 return UUIDResponse(content)30 }31}32class ObjectTest : MockHttpTestCase() {33 private fun randomUUID() = UUID.randomUUID()34 private fun getUUID(uuid: UUID, path: String = "uuid"): Request {35 mock.chain(36 request = mock.request().withPath("/$path"),37 response = mock.response().withBody(uuid.toString())38 )39 return Fuel.request(Method.GET, mock.path(path))40 }41 private fun mocked404(method: Method = Method.GET, path: String = "invalid/url"): Request {...

Full Screen

Full Screen

Models.kt

Source:Models.kt Github

copy

Full Screen

...43 val bitmap: Bitmap? = BitmapFactory.decodeByteArray(it, 0, it.size)44 if (bitmap != null) {45 handler(Result.success(bitmap))46 } else {47 handler(Result.error(FuelError.wrap(NullPointerException()))) // 可能是张gif,不支持48 }49 return50 }51 news.imageList[which].httpGet().response { _, _, result ->52 result.map { BitmapFactory.decodeByteArray(it, 0, it.size) }.apply(handler)53 result.success { imageDataList[which] = it }54 }55 }56 // 调用者保证news.video非空57 // handler处理的是视频文件名(因为视频播放器库不接受视频内容,只接受url)58 inline fun downloadVideo(crossinline handler: (String) -> Unit) {59 val video = news.video!!60 val videoPath = videoPath ?: run {61 handler(video) // 如果没有本地下载,则直接播放video网址(这样用户不需要等待)...

Full Screen

Full Screen

SuspendableRequest.kt

Source:SuspendableRequest.kt Github

copy

Full Screen

...7import com.github.kittinunf.result.Result8/**9 * Coroutine version of [RequestTask]. Turns a [Request] into an executable, suspendable, coroutine.10 */11class SuspendableRequest private constructor(private val wrapped: Request) : Request by wrapped {12 private val interruptCallback by lazy { executor.interruptCallback }13 private val executor by lazy { request.executionOptions }14 private val client by lazy { executor.client }15 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)16 private suspend fun executeRequest(request: Request): Pair<Request, Response> {17 return runCatching { Pair(request, client.awaitRequest(request)) }18 .recover { error -> throw FuelError.wrap(error, Response(url)) }19 .getOrThrow()20 }21 private fun prepareResponse(result: Pair<Request, Response>): Response {22 val (request, response) = result23 return runCatching { executor.responseTransformer(request, response) }24 .mapCatching { transformedResponse ->25 val valid = executor.responseValidator(transformedResponse)26 if (valid) transformedResponse27 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)28 }29 .recover { error -> throw FuelError.wrap(error, response) }30 .getOrThrow()31 }32 suspend fun awaitResult(): Result<Response, FuelError> {33 return runCatching { prepareRequest(request) }34 .mapCatching { executeRequest(it) }35 .mapCatching { pair ->36 // Nested runCatching so response can be rebound37 runCatching { prepareResponse(pair) }38 .recover { error ->39 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }40 throw FuelError.wrap(error, pair.second)41 }42 .getOrThrow()43 }44 .onFailure { error ->45 Fuel.trace { "[RequestTask] on failure ${(error as? FuelError)?.exception ?: error}" }46 if (error is FuelError && error.causedByInterruption) {47 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }48 interruptCallback.invoke(request)49 }50 }51 .map { Result.Success(it) }52 .recover { Result.Failure(it as FuelError) }53 .getOrThrow()54 }...

Full Screen

Full Screen

HttpUpstream.kt

Source:HttpUpstream.kt Github

copy

Full Screen

...68 return retryGet(url)69 }70 result71 } catch (e: Exception) {72 Result.error(FuelError.wrap(e))73 }74 }75 private suspend fun retryGet(url: String): Result<R, FuelError> {76 return try {77 return if (HTTP.refresh()) {78 val request = Fuel.get(mustNormalizeUrl(url)).apply {79 if (!Settings.isAnonymous()) {80 header("Authorization", "Bearer ${Settings.getAccessToken()}")81 }82 }83 request.awaitObjectResult(GenericDeserializer(type))84 } else {85 Result.Failure(FuelError.wrap(RefreshError))86 }87 } catch (e: Exception) {88 Result.error(FuelError.wrap(e))89 }90 }91}...

Full Screen

Full Screen

Data.kt

Source:Data.kt Github

copy

Full Screen

...48 }49 }50 request.awaitObjectResult(gsonDeserializerOf(T::class.java))51 } else {52 Result.Failure(FuelError.wrap(RefreshError))53 }54 }55}56object Cache {57 private fun key(key: String): String {58 val md = MessageDigest.getInstance("SHA-1")59 val digest = md.digest(key.toByteArray(Charset.defaultCharset()))60 return digest.fold("", { acc, it -> acc + "%02x".format(it) })61 }62 fun set(context: Context?, key: String, value: ByteArray) = context?.let {63 with(File(it.cacheDir, key(key))) {64 writeBytes(value)65 }66 }...

Full Screen

Full Screen

RequestTask.kt

Source:RequestTask.kt Github

copy

Full Screen

...16 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)17 @Throws(FuelError::class)18 private fun executeRequest(request: Request): RequestTaskResult {19 return runCatching { Pair(request, client.executeRequest(request)) }20 .recover { error -> throw FuelError.wrap(error, Response(request.url)) }21 .getOrThrow()22 }23 @Throws(FuelError::class)24 private fun prepareResponse(result: RequestTaskResult): Response {25 val (request, response) = result26 return runCatching { executor.responseTransformer(request, response) }27 .mapCatching { transformedResponse ->28 val valid = executor.responseValidator(transformedResponse)29 if (valid) transformedResponse30 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)31 }32 .recover { error -> throw FuelError.wrap(error, response) }33 .getOrThrow()34 }35 @Throws(FuelError::class)36 override fun call(): Response {37 return runCatching { prepareRequest(request) }38 .mapCatching { executeRequest(it) }39 .mapCatching { pair ->40 // Nested runCatching so response can be rebound41 runCatching { prepareResponse(pair) }42 .recover { error ->43 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }44 throw FuelError.wrap(error, pair.second)45 }46 .getOrThrow()47 }48 .onFailure { error ->49 Fuel.trace { "[RequestTask] on failure (interrupted=${(error as? FuelError)?.causedByInterruption ?: error})" }50 if (error is FuelError && error.causedByInterruption) {51 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }52 interruptCallback.invoke(request)53 }54 }55 .getOrThrow()56 }57}58internal fun Request.toTask(): Callable<Response> = RequestTask(this)...

Full Screen

Full Screen

RequestTaskCallbacks.kt

Source:RequestTaskCallbacks.kt Github

copy

Full Screen

...23 override fun call(): Response {24 Fuel.trace { "[RequestTaskCallbacks] start request task\n\r\t$request" }25 return runCatching { task.call() }26 .mapCatching { it -> it.also { onSuccess(it) } }27 .getOrElse { error -> FuelError.wrap(error).also { onFailure(it, it.response) }.response }28 }29}...

Full Screen

Full Screen

wrap

Using AI Code Generation

copy

Full Screen

1val wrappedError = error . wrap () 2 println (wrappedError)3val unwrappedError = wrappedError . unwrap () 4 println (unwrappedError)5val error = Exception ( "Exception occurred" ) . asError () 6 println (error)7 val error = Exception ( "Exception occurred" ) . asError () 8 println (error . exception ) 9 println (error . exception ) 10 println (error . response ) 11 println (error . response ) 12 println (error . request ) 13 println (error . request ) 14 println (error . message ) 15 println (error . message ) 16 println (error . isDeserializationError ) 17 println (error . isDeserializationError ) 18 println (error . isServerError ) 19 println (error . isServerError ) 20 println (error . isClientError ) 21 println (error . isClientError ) 22 println (error . isConnectionError ) 23 println (error . isConnectionError ) 24 println (error . isResponseError ) 25 println (error . isResponseError ) 26 println (error . isRequestError ) 27 println (error . isRequestError ) 28 println (error . isOtherError ) 29 println (error . isOtherError )30 val error = Exception ( "Exception occurred" ) . asError () 31 println (error . wrap ()) 32 println (error . wrap ()) 33 println (error . wrap (). unwrap ()) 34 println (error . wrap (). unwrap ()) 35 println (error . wrap (). unwrap (). wrap ()) 36 println (error . wrap (). unwrap (). wrap

Full Screen

Full Screen

wrap

Using AI Code Generation

copy

Full Screen

1val error = result.third.get()2println(error.wrap())3val error = result.third.get()4println(error.wrap())5val error = result.third.get()6println(error.wrap())7val error = result.third.get()8println(error.wrap())9val error = result.third.get()10println(error.wrap())11val error = result.third.get()12println(error.wrap())13val error = result.third.get()14println(error.wrap())15val error = result.third.get()16println(error.wrap())17val error = result.third.get()18println(error.wrap())19val error = result.third.get()20println(error.wrap())

Full Screen

Full Screen

wrap

Using AI Code Generation

copy

Full Screen

1val error = FuelError (Exception( "Something went wrong" ))2val wrappedError = error .wrap( "This is a wrapped error" )3println(wrappedError.message)4val error = FuelError (Exception( "Something went wrong" ))5val wrappedError = error .wrap( "This is a wrapped error" )6val unwrappedError = wrappedError.unwrap()7println(unwrappedError.message)8val error = FuelError (Exception( "Something went wrong" ))9val wrappedError = error .wrap( "This is a wrapped error" )10val unwrappedError = wrappedError.unwrap()11println(unwrappedError.message)12val error = FuelError (Exception( "Something went wrong" ))13val wrappedError = error .wrap( "This is a wrapped error" )14val unwrappedError = wrappedError.unwrap()15println(unwrappedError.message)16val error = FuelError (Exception( "Something went wrong" ))17val wrappedError = error .wrap( "This is a wrapped error" )18val unwrappedError = wrappedError.unwrap()19println(unwrappedError.message)20val error = FuelError (Exception( "Something went wrong" ))21val wrappedError = error .wrap( "This is a wrapped error" )22val unwrappedError = wrappedError.unwrap()23println(unwrappedError.message)24val error = FuelError (Exception( "Something went wrong" ))25val wrappedError = error .wrap( "This is a wrapped error" )26val unwrappedError = wrappedError.unwrap()27println(unwrappedError.message)28val error = FuelError (Exception( "Something went wrong" ))29val wrappedError = error .wrap( "This is a wrapped error" )

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in FuelError

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful