laravel 4 - Implementing a try/catch block in php constructor function -


i have query try-catch block. going create object , if fails throw error message or redirect on 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 example method not want set  } 

is correct way define , use try catch block in constructor? can use try & catch block in construction? if no there better way achieve this?

thanks in advance!!!

you can use try catch in constructor, don't forget specify exception class want catch catch (\exception $e). laravel not process returned redirect. (by definition constructors shouldn't return something)

an easy fix calling send() on redirect. return client , stop app.

try{      $this->serviceobj = anyclass::getservice('xxx'); } catch(\exception $e){     redirect::to('/')->send(); } 

but since mentioned login page, might better of using before filter check , redirect. built in auth filter does.

a third solution app::error. in app/start/global.php this:

app::error(function(foobarexception $exception) {     return redirect::to('/'); }); 

of course works if exception specific enough (replace foobarexception exception want catch)


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -