Handling network call errors in Kotlin

栏目: IT技术 · 发布时间: 4年前

内容简介:When designing how to handlenetwork calls in your app, you might think that you are done as soon as you define your interface. You are halfway there: you have defined the "happy" path. But what happens when not everything goes according to plan? That's the

When designing how to handlenetwork calls in your app, you might think that you are done as soon as you define your interface. You are halfway there: you have defined the "happy" path. But what happens when not everything goes according to plan? That's the other half.

As always, a reminder that there are no completely right or wrong answers here. It's rather a matter of choosing the most suitable approach depending on your requirements and your app architecture to make your life easier in the long run.

The straightforward way: try-catch statements

An error is by definition an exception to the normal flow of the app. Kotlin supports exception throwing and catching quite smoothly. So, all you have to do is throw the correct exception when an issue arises from the network library.

To make your code network library independent, a good approach is to create your own BaseNetworkException class and create an exception class for each type of error that can happen.

viewModelScope.launch {
    try {
        callService()
    }
    catch (e: NoNetworkException) {
        // Handle it
    }
    catch (e: AuthenticationNetworkException) {
        // Handle it
    }
}

The downside here is that you need to wrap every network call with a try-catch statement. If you forgot about it and an error occurs, your app will crash.

The modern way: return Result

A network call can either succeed or fail. So a Result class should represent exactly this: a success state with the data, or a failed state with the exception.

Kotlin has a built-in Result but when trying to use it as a return type you will get kotlin.Result' cannot be used as a return type ( why ). You can either create your own Result class , use an open-source alternative , or use a hack to use the standard library Result (not really recommended since it can break your build in the future).

viewModelScope.launch {
    callService().fold(
        { data ->
            // Successful call
        }, 
        { error ->
            if (error is NoNetworkException) {
                // Hanlde it
            }
            else if (error is AuthenticationNetworkException) {
                // Hanlde it
            }
        }
}

Using this approach you are forced to handle the potential error. The downside might be that it gets repetitive, especially if handling the same generic errors (but this can be fixed by using common handler methods).

The coroutine way: CoroutineExceptionHandler

The launch coroutine builder accepts a default exception handler parameter. The handler is activated only within the scope of the coroutine. This could be convenient for handling all the "common" exceptions (e.g. no internet connection). With this approach, there's no need to repeat how to handle common errors.

Any errors not handled by the coroutine exception handler will still have to be handled by one of the previous ways (or create specific CoroutineExceptionHandler instances).

val genericErrorHandler = CoroutineExceptionHandler { _, error ->
    if (error is NoNetworkException) {
        // Hanlde it
    }
    else if (error is AuthenticationNetworkException) {
        // Hanlde it
    }
}

[...]

viewModelScope.launch(genericErrorHandler) {
    callService()
}

Hopefully, by now you have a bit clearer picture on how to handle your network errors. Happy coding!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

创新者

创新者

[美] 沃尔特·艾萨克森 / 关嘉伟、牛小婧 / 中信出版社 / 2017-4 / 88.00元

《创新者》是沃尔特·艾萨克森继全球畅销书《史蒂夫·乔布斯传》之后的又一部力作,不仅讲述了计算机和互联网从无到有的发展历程,为我们 生动地刻画出数字时代的创新者群像,还深度挖掘互联网的精神内核,解读了“诗意科学”这个重大主题。 在近200年的数字化进程中群星闪耀,艾萨克森从第一个计算机程序的创造者、浪漫主义诗人拜伦之女埃达•洛夫莱斯伯爵夫人说起,细数了这一群将科学与人文融合的创新者,他们包括第......一起来看看 《创新者》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具