Handle various HTTP status code by safe api call with Result sealed class

Overview

retrofit2-safe-api-call

Handle various HTTP status code by safe api call with Result sealed class

Library

  • Retrofit2
  • OkHttp3
  • Gson
  • Coroutine
  • DI : Koin
  • ViewModel
  • LiveData
  • Timber

Code

ResultWrapper

package com.example.retrofithandlestatus.util

sealed class ResultWrapper<out T> {
    data class Success<out T>(val data: T) : ResultWrapper()
    data class GenericError(val code: Int?, val message: String?) : ResultWrapper()
    object NetworkError : ResultWrapper<Nothing>()
}

SafeApiCall

suspend fun <T> safeApiCall(
    dispatcher: CoroutineDispatcher,
    apiCall: suspend () -> T
): ResultWrapper<T> {
    return withContext(dispatcher) {
        try {
            ResultWrapper.Success(apiCall.invoke())
        } catch (throwable: Throwable) {
            when(throwable) {
                is IOException -> ResultWrapper.NetworkError
                is HttpException -> {
                    val code = throwable.code()
                    val errorBody = throwable.response()?.errorBody()?.string()
                    Timber.d(code.toString())
                    Timber.d(errorBody)
                    val gsonErrorBody = Gson().fromJson(
                        errorBody,
                        ErrorBody::class.java
                    )
                    val message = gsonErrorBody.message
                    ResultWrapper.GenericError(code, message)
                }
                else -> ResultWrapper.GenericError(null, null)
            }
        }
    }
}
  • Use string() method instead of toString()
val errorBody = throwable.response()?.errorBody()?.string()

Next Step

Reference

https://medium.com/@douglas.iacovelli/how-to-handle-errors-with-retrofit-and-coroutines-33e7492a912

You might also like...
Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

OkHttp See the project website for documentation and APIs. HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP

HTTP Server for Android Instrumentation tests

RESTMock REST API mocking made easy. RESTMock is a library working on top of Square's okhttp/MockWebServer. It allows you to specify Hamcrest matchers

🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀
🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀

Fast Android Networking Library About Fast Android Networking Library Fast Android Networking Library is a powerful library for doing any type of netw

Multiplatform coroutine-based HTTP client wrapper for Kotlin

networkinkt This is a lightweight HTTP client for Kotlin. It relies on coroutines on both JS & JVM platforms. Here is a simple GET request: val text =

Kotlin HTTP requests library. Similar to Python requests.

khttp khttp is a simple library for HTTP requests in Kotlin. It functions similarly to Python's requests module. import khttp.get fun main(args: Arra

Kotlin DSL http client
Kotlin DSL http client

Introduction Kotlin DSL http client Features 🔹 Developers Experience-driven library without verbosity. 🔹 Native way to use http client in Kotlin. 🔹

The easiest HTTP networking library for Kotlin/Android

Fuel The easiest HTTP networking library for Kotlin/Android. You are looking at the documentation for 2.x.y.. If you are looking for the documentation

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Java HTTP Request Library

Http Request A simple convenience library for using a HttpURLConnection to make requests and access the response. This library is available under the

Owner
Jaesung Lee
Android Developer
Jaesung Lee
HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps

HttpMocker HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries. It ca

David Blanc 174 Nov 28, 2022
A type-safe HTTP client for Android and the JVM

Retrofit A type-safe HTTP client for Android and Java. For more information please see the website. Download Download the latest JAR or grab from Mave

Square 41k Jan 5, 2023
Helmet secures your spring Webflux or MVC app by setting various HTTP headers

Helmet Helmet secures your spring Webflux or MVC app by setting various HTTP headers. This is a 1:1 copy of Helmet.js Quick start Add https://jitpack.

Dušan 1 Oct 28, 2021
Android Easy Http - Simplest android http request library.

Android Easy Http Library 繁體中文文檔 About Android Easy Http Library Made on OkHttp. Easy to do http request, just make request and listen for the respons

null 13 Sep 30, 2022
A js websocket server that handle an android app that connect to the sever with a QR code, to move a red square on a webpage with the gyroscope and accelerometer

online game a js websocket server with an express server, with a mobile app. backend express is used to handle the creation page, game page and the cr

null 2 Oct 7, 2021
A library that observes your network status.

A library that observes your network status. Update in progress ... Download Using gradle In your root build.gradle at the end of repositories add all

Moses Wangira 9 Apr 18, 2022
Write your asynchronous Network / IO call painlessly in Kotlin !!

Asynkio : Write asynced IO/ Network calls painlessly on android | | | Documentation Write your network requests, IO calls in android with Kotlin seaml

Nikhil Chaudhari 82 Jan 26, 2022
Retrofit Flow Call Adapter Factory For Android

Summary Android Retrofit FlowCallAdapterFactory Retrofit 2 CallAdapter.Factory f

TaeHwan 12 Aug 3, 2022
SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network requests with HttpURLConnection.

SimpleApiCalls ?? SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network reque

null 4 Nov 28, 2022
Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

AsyncHttpClient 6k Jan 8, 2023