Rumah  >  Artikel  >  pembangunan bahagian belakang  >  如何在yii2-wx中使用try_catch

如何在yii2-wx中使用try_catch

不言
不言asal
2018-07-10 14:52:531800semak imbas

这篇文章主要介绍了关于如何在yii2-wx中使用try_catch,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

至于为何要使用try...catch...结构我不想多说,本帖说说在yii2-wx中如何使用它。

也就是说在yii2-wx中有几个Exception是我们需要关注的?大家知道yii2-wx是一个通讯类的库,基本上每个方法都有和微信服务器发起请求的操作,在模拟http客户端这里我们使用的是yii的官方扩展yii2-httpclient。

所以当我们使用yii2-wx的时候,第一步要捕获的就是客户端异常,如下代码

try {
    $qrcodeFile = $qrcode->strTemp(300,$code);
}catch(\yii\httpclient\Exception $e){
    // todo
}

这是在通讯这里我们要去捕获 yiihttpclientException 异常。

接下来说说yii2-wx的解构,做为一个单入口扩展,Application类是非常重要的,而这个类也有异常的抛出,比如当你使用driver驱动一个接口助手对象的时候,接口的名字不正确,这个抛出使用yii2-wx内置的Exception,所以正确使用driver的方法如下

try {
    $app = new Application(['conf'=>$conf['mp']]);    
    $qrcode = $app->driver("mp.qrcode");
}catch(\abei2017\wx\core\Exception $e){
    // todo
}

上面说了整体框框,接下来说具体的方法,比如当我们使用$qrcode->strTemp(300,$code)的时候,通讯没有问题,但是获取二维码结果出问题了,此刻这些助手的方法也会抛出一个 abei2017wxcoreException 异常,可以在$e->getMessage()中拿到信息。

最后总结说一下完整的yii2-wx代码编写结构。

try {
    $app = new Application(['conf'=>$conf['mp']]);
    $qrcode = $app->driver("mp.qrcode");
    $code = Yii::$app->security->generateRandomString();
    $qrcodeFile = $qrcode->strTemp(300,$code);
    
}catch(\abei2017\wx\core\Exception $e){
    // todo
}catch(\yii\httpclient\Exception $e){
    // todo
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Yii2中GridView的用法总结

关于php如何调用phantomjs给微信小程序分享的问题

Atas ialah kandungan terperinci 如何在yii2-wx中使用try_catch. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn