Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I throw a custom try-catch exception on CakePHP?

I want to throw a custom exception which is the data validation exception in a controller of my CakePHP application. How do I create my own custom exception handler in Cakephp so that I can throw the exception and catch the exception?

My code example:

function getUserDetails($userid){

    try{
         if(!$validUser){
              throw new Exception('Invalid User');
         }

         return $userDetailsData;  //returned from db
    }catch(Exception $e){
         echo 'Error:'.$e->getMessage();
        return;
    }

}

is it possible to use here custom Exception class in cakephp so that only those exception can be thrown that what i do. Hope it clarifies question. thanks.

like image 943
shakil Avatar asked Mar 29 '26 15:03

shakil


1 Answers

CakePHP actually depends heavily on namespaces.

Adding \ to Exception should solve your problem.

 }catch(\Exception $e){

If you want something more, you can create an exception class and get the object from that namespace.

like image 200
Süha Boncukçu Avatar answered Mar 31 '26 12:03

Süha Boncukçu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!