繁体   English   中英

在php构造函数中实现try / catch块

[英]Implementing a try/catch block in php constructor function

我有一个try-catch块查询。 我将创建对象,如果失败,它将引发错误消息或在其他页面上重定向。

function __construct() {
        try{ 
            $this->ServiceObj = AnyClass::getService('XXX');
          }
        catch{
            return Redirect::to('/');
        }
    } 

public function MyOwnFunction() {

    $getValueofCode = $this->_ServiceObj->set($endPoint_Url); //it's only example method not want to set anything
 }

这是在构造函数中定义和使用try catch块的正确方法吗? 我可以在建筑中使用试挡块吗? 如果没有 ,有没有比这更好的方法了?

提前致谢!!!

您绝对可以在构造函数中使用try catch,只是不要忘记像catch (\\Exception $e)这样指定要捕获的异常类。 但是,Laravel将不会处理返回的重定向。 (通过定义构造函数甚至不应该返回任何东西)

一个简单的解决方法是在重定向上调用send() 这将立即将其返回给客户端并停止该应用程序。

try{ 
    $this->ServiceObj = AnyClass::getService('XXX');
}
catch(\Exception $e){
    Redirect::to('/')->send();
}

但是,由于您提到了登录页面,因此最好使用before过滤器进行检查和重定向。 就像内置的auth过滤器一样。

第三种解决方案是App::error app/start/global.php您可以执行以下操作:

App::error(function(FooBarException $exception)
{
    return Redirect::to('/');
});

当然,这仅在您的异常足够具体时才起作用(将FooBarException替换为您要捕获的异常)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM