简体   繁体   English

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

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

I have a query with try-catch block. 我有一个try-catch块查询。 I am going to create object and if it fails it will throw error message or say redirect on some other page. 我将创建对象,如果失败,它将引发错误消息或在其他页面上重定向。

Code

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
 }

Is this correct way to define and use the try catch block in a constructor? 这是在构造函数中定义和使用try catch块的正确方法吗? Can I use try & catch block in construction? 我可以在建筑中使用试挡块吗? If NO than is there a better way to achieve this? 如果没有 ,有没有比这更好的方法了?

Thanks in Advance!!! 提前致谢!!!

You can definitely use try catch in a constructor, just don't forget to specify the exception class you want to catch like catch (\\Exception $e) . 您绝对可以在构造函数中使用try catch,只是不要忘记像catch (\\Exception $e)这样指定要捕获的异常类。 However Laravel will not process the returned redirect. 但是,Laravel将不会处理返回的重定向。 (By definition constructors shouldn't even return something) (通过定义构造函数甚至不应该返回任何东西)

An easy fix for this would be calling send() on the redirect. 一个简单的解决方法是在重定向上调用send() This will return it immediately to the client and stop the app. 这将立即将其返回给客户端并停止该应用程序。

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

But since you mentioned a login page, you might be better of using a before filter to check and redirect. 但是,由于您提到了登录页面,因此最好使用before过滤器进行检查和重定向。 Like the built in auth filter does. 就像内置的auth过滤器一样。

A third solution would be App::error . 第三种解决方案是App::error In app/start/global.php you could do something like this: app/start/global.php您可以执行以下操作:

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

Of course this only works if your exception is specific enough (replace FooBarException with the exception you want to catch) 当然,这仅在您的异常足够具体时才起作用(将FooBarException替换为您要捕获的异常)

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

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