Nabeel Arshad
Nabeel Arshad

Reputation: 45

how to handle HTTPErrorException in php

I am confused in an issue. I have thrown an exception for unauthorized user in a function. When I call this function it shows *Fatal error: Uncaught exception 'HTTPErrorException' * My code is

throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );

How can I catch this Exception so that I can show some CSS instead of the stack trace which is comming

Upvotes: 1

Views: 185

Answers (1)

Saket Patel
Saket Patel

Reputation: 6683

the error code shows that you haven't caught the exception, so it will throw this error. every exception should be caught by your code

try {
  ....
  throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
  ....
} catch (HTTPErrorException $e) {
  // generate a stack trace here and show it to user
  // you can use $e->getTraceAsString() or $e->getTrace() functions here to get stack trace
}

or if you don't want to use try / catch blocks then you can create a exception handler function that will be called whenever your application has not caught the exception anywhere

function exception_handler($exception) {
  echo "Custom Exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

check more about exceptions http://php.net/manual/en/language.exceptions.php

Upvotes: 3

Related Questions