在 Swift 中转发错误 [英] Forwarding an error in Swift

查看:26
本文介绍了在 Swift 中转发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的解决方案将 Swift 错误从一个函数转发到另一个函数?

Is there a better solution to forward a Swift error from one function to another?

目前,我是这样做的:

enum Error:ErrorType{

    case Error1
    case Error2
}

func func1()throws{
     do{
         try func2()

        }catch Error.Error1{
            throw Error.Error1

        }catch Error.Error2{
            throw Error.Error2
        }
}

func func2()throws{
     // proof something
     throw Error.Error1
}

因此,要转发错误,我需要捕获所有错误并再次抛出它们.

So, to forward an error, I need to catch all the errors and throw them again.

有更好的解决方案吗?

推荐答案

是的:不要将其包装在 do ... catch 块中.

Yes: don't wrap it in a do ... catch block.

func func2() throws{
     // proof something
     throw Error.Error1
}

func func1()throws{
     try func2()
}

这篇关于在 Swift 中转发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆