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

10.7k views Asked by At

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.

1

There are 1 answers

2
Süha Boncukçu On

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.