How can I add a try-catch exception on CakePHP?

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

My sample code is:

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 the special Exception class in cakephp here so that only this exception can be thrown, which I am doing. I hope he clarifies the question. thanks.

+1
exception throw try-catch cakephp
source share
1 answer

CakePHP is actually heavily dependent on namespaces.

Adding \ to Exception should solve your problem.

  }catch(\Exception $e){ 

If you want something else, you can create an exception class and get an object from this namespace.

+5
source share

All Articles