美文网首页KotlinKotlin
[译] Kotlin中使用runcatching函数式处理错误

[译] Kotlin中使用runcatching函数式处理错误

作者: 两三行代码 | 来源:发表于2019-09-30 23:24 被阅读0次

     Kotlin1.3已经发布一年有余,也带来了很多改变。其中,runCatchingmapCatching使我异常激动。对于错误,开发这通常需要做两件事情:

    • 忽略
    • 使错误不断增长,或者采取措施作出改善

    让我们看看传统处理错误的方法:

    fun main() { 
        try {
            val value = getRandomNumber()
            println("The random number we get is -> $value")
        } catch (e: Exception) {
            System.err.println("Error occurred -> ${e.message}")
        }
    }
    
    @Throws(Exception::class)
    private fun getRandomNumber(): Int {
        val randomNumber = (1..20).shuffled().first()
        if (randomNumber % 2 == 0)
            return randomNumber
        else
            throw Exception("The random number is odd.")
    }
    

    &emsp上述代码没有问题,也能够try{}catch{}捕获异常,但是kotlin强烈建议我们使用函数式风格或者链式风格编程。

    函数式风格错误处理

     现在如果我们尝试处理异常,以Single
    作为返回类型,函数式风格处理潜在错误。

    fun main() {
         getRandomNumber()
               .subscribe({ 
                    println(it) 
               }, { 
                    System.err.println(it.message) 
               })
    }
    

     上述函数式风格代码完全不同于直接编程的方式。getRandomNumber风格简单地返回Single<Int>,它什么也没有做,直到调用subscribe方法。
     现在我们看上面代码则更加符合语言习惯,本质上也更加函数化。自kotlin1.3版本之后,其标准库提供了同样的功能,不需要引入外部依赖。

    使用runCatching函数式处理错误

    首先我们看下runCatching的实现原理:

    public inline fun <R> runCatching(block: () -> R): Result<R> {
        return try {
            Result.success(block())
        } catch (e: Throwable) {
            Result.failure(e)
        }
    }
    

      runCatching在try{}catch{e: Throwable}内执行指定的代码块,如果调用成功,则返回结果,如果失败,则抛出异常。你可以点击link查看更多。
     以下代码展示了runCatching函数式处理异常的例子:

    @Throws(Exception::class)
    private fun getRandomNumber(): Int {
        val randomNumber = (1..20).shuffled().first()
        if (randomNumber % 2 == 0)
            return randomNumber
        else
            throw Exception("The random number is odd.")
    }
    
    fun main() {
        runCatching {
            getRandomNumber()
        }.onSuccess {
            println(it)
        }.onFailure {
            System.err.println(it.message)
        }
    }
    

    如果getRandomNumber方法抛出异常,那么onFailure方法就会被调用,并且伴随异常信息,另外,如果执行成功,那么onSuccess方法会被调用。

     对于并行异步计算,也能够正确获取成功或异常信息。

    import kotlinx.coroutines.Deferred
    import kotlinx.coroutines.GlobalScope
    import kotlinx.coroutines.async
    
    suspend fun main()  {  
        val deferreds: List<Deferred<Int>> = List(10) {  // 1
            GlobalScope.async {   // 2
                if (it % 2 == 0)
                    return@async it
                else
                    throw Exception("The odd number comes inside the list")
            }
        }
        deferreds.map { // 3
            return@map runCatching { 
                return@runCatching it.await()   // 4
            }
        }.forEach {
            it.onSuccess { value ->  // 5
                println(value)
            }.onFailure { t ->  // 6
                System.err.println(t.message)
            }
        }
    }
    

    以上代码执行内容如下:
    1、创建一个从0到9的Integer列表;
    2、创建协程,如果数字为偶数,返回 Deferred<Int>,如果是奇数,返回则抛出Exception
    3、对于<Deferred>应用map转换;
    4、在runCatching方法内部,封装Deferred await结果。如果发生潜在错误,则将错误传递给下游;
    5、对于偶数,调用onSuccess方法并且在控制台打印输出;
    6、对于奇数,调用onFailure方法并且打印出错误;

    我们在异步编程中书写函数式异常处理代码也无需引用三方库。

    在Result<T>中使用mapCatching处理转换###

     有时候,我们对于single Result<T>会在检查错误或者成功之前应用map transformation。

    abstract fun readBitmap(file :File) : Bitmap
    
    fun readBitmapsWithCatching(files : List<File>) : List<Result<Bitmap>> {
        files.map {
            runCatching { file ->  
                 return@runCatching readBitmap(file)
            }
        }
    }
    
    readBitmapsWithCatching(files).map { result ->
        result.map { bitmap ->
             processBitmap(bitmap)
        }
    }
    

     在上述例子中,readBitmap接受一个文件类型参数,返回Bitmap类型值。readBitmap方法会抛出异常,如果文件not found或者bitmap not found。通常,我们的代码会捕获异常,因为方法被封装调用在runCatchingreadBitmapWithCatching

     在上述代码中,如果processBitmap方法在处理图片过程中抛出异常,那么应用将会崩溃,所以我们需要使用mapCatching而不是map。

    readBitmapsWithCatching(files).map { result ->
       result.mapCatching { bitmap ->
            processBitmap(bitmap)
       }
    }
    

    原文参考 A FUNCTIONAL WAY OF HANDLING ERROR IN KOTLIN WITH RUNCATCHING

    相关文章

      网友评论

        本文标题:[译] Kotlin中使用runcatching函数式处理错误

        本文链接:https://www.haomeiwen.com/subject/cvpgyctx.html