简体   繁体   中英

Implementing a try/catch block in php constructor function

I have a query with try-catch block. 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? 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) . However Laravel will not process the returned redirect. (By definition constructors shouldn't even return something)

An easy fix for this would be calling send() on the redirect. 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. Like the built in auth filter does.

A third solution would be App::error . In app/start/global.php you could do something like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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