Handle php errors - php

I'm trying to catch and throw php errors as an exception
set_exception_handler(function($e){
echo $e->getMessage();
});
register_shutdown_function(function() {
$error = error_get_last();
if ($error['type'] === E_ERROR) {
throw new ErrorException($error['message'], 0);
}
});
notExistingFunction();
The problem is that ErrorException is not "catched" by my exception handler and I get
Uncaught exception 'ErrorException' with message 'Call to undefined function notExistingFunction()'
instead of a nice message.

set_exception_handler( 'ExceptionHandler' );
http://php.net/manual/en/function.set-exception-handler.php
In your case:
set_exception_handler( 'notExistingFunction' );

try{
//your code
} catch (Exception $e) {
//do something with errr
}

Related

Can someone explain my how this exceptions works?

I found an really interesting problem on the internet about Exceptions & Errors, but I can't get it.
class MyException extends Exception {
public function __construct(string $message) {
$this -> message = $message;
}
}
class A {
public function __construct() {
throw new MyException("an error appeared");
}
}
$err = null;
try {
new A();
}
catch (MyException $err) {
throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
When I execute the code I receive
Fatal error: Uncaught Exception: another error appeared in C:\xampp
I don't understand if it's a problem about the code or this is how it works actually. Maybe you can help me.
That fatal error is for an untreated exception?
Thank you!
The second catch block does not catch the exception thrown in the first catch block. It can only be used to catch a an additional type of exception thrown in the first try block.
To catch your second exception you need to add a nested try catch:
try {
new A();
}
catch (MyException $err) {
try {
throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
}
Yes, the fatal error is for an unhandled exception here:
$err = null;
try {
new A();
}
catch (MyException $err) {
--->throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
In case you are wondering what is leading to this, it is this line in your code snippet:
$err = null;
try {
---> new A();
}

Exception not able to get caught in catch block - Yii2

Exception
Exception 'Error' with message 'Class 'app\commands\CallLogs' not
found'
is not able to get caught in catch block.
Code:
I tried with calling undefined class just to see how and what exception catch block catches.
public function actionTest(){
try {
$logs = new CallLogs();
} catch (\yii\base\Exception $ex) {
print $ex->getMessage();
} catch(\ErrorException $ex){
print $ex->getMessage();
}
}
But, When I intentionally throw any exception, it works.
public function actionTest(){
try {
throw new \yii\base\Exception('hello');
} catch (\yii\base\Exception $ex) {
print $ex->getMessage();
} catch(\ErrorException $ex){
print $ex->getMessage();
}
}
I have tried with base\Exception class and \ErrorException class. But, no help.
Any help/hint is appreciable
catch (\Throwable $e) will do the job
\Throwable was introduced back in PHP 7.0 and is (quoting from docs) used for
[...] any object that can be thrown via a throw statement, including
Error and Exception.

PHP Exception couldn't work

Having read the article on this site here, I wrote this following code :
<?php
try{
annundefinedmethod();
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
?>
I wanted to show an error based on the proper exception for the function calling in the try block. However, all above exceptions didn't work, I still got an error saying uncaught error : call to undefined method.... what has gone wrong with my code?
You can't catch fatal errors in PHP. You may use 'is_callable' or 'function_exists' for this situation.
You may throw your own catch if you like:
try{
if (!is_callable('annundefinedmethod')) {
throw new BadFunctionCallException();
}
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
Quite simply an undefined method isn't the code throwing an exception.
try{
throw new Exception;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
You can also pass and call messages through in your exceptions and write them out in the catch block:
try{
throw new Exception('some useful error message');
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo $e->getMessage();
}
This is the same for the other type of exceptions you mention:
try{
throw new RuntimeException;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
And
try{
throw new BadFunctionCallException;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
In PHP 5.x, you have to explicitly test if the function is callable first. You can't catch this type of error.
In PHP 7, errors such as this one are actually Error objects that implement Throwable. Error is a the new PHP 7 new base class for thrown internal PHP errors.
In this particular case, you are actually getting an Error object that implements Throwable. If you add a catch on either one of those types, you will be able to catch this error.
try {
annundefinedmethod();
}
catch (Error $e) {
//$e->getMessage() == "Call to undefined function annundefinedmethod()"
}

Propagate exception to next catch

i have this code:
<?php
[...]
// Authentication error
catch(AuthException $e)
{
// TODO: Save fault to auth into DB
// Propagate exception
throw $e;
}
// Common exception
catch(Exception $e)
{
// TODO: Log error here
$response = JsonResponse(array("error" => $e->getMessage()));
$response->send();
}
I want to able to throw AuthException and Exception, and want to be sure that AuthException's catch will store error into db, and as common Exception will be returned as error.
But now I have error, that I have uncaugth exception.
Or maybe I need to log error in the AuthException's constructor?
You don't need to catch each exception, I guess you wanna do something like this ?
try {
//...
} catch(Exception $e){
if($e instanceof AuthException ) {
// Log error here
}
$response = JsonResponse(array("error" => $e->getMessage()));
$response->send();
}

XML Exception in PHP not being caught

My code snippet is below - as you can see, I have a try-catch block, but inspite of this, I still get an uncaught exception that terminates the entire application. What am I missing?
try {
$cakeXml = simplexml_load_string($xml);
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
2014-12-16 22:45:12 Error: Fatal Error (1): Call to a member function xpath() on a non-object
2014-12-16 22:45:12 Error: [FatalErrorException] Call to a member function xpath() on a non-object
If you read the error message more-carefully, you will see that it is not dieing on an Exception, but on a Fatal Error. A try/catch statement cannot catch a fatal error in PHP, as there is no way to recover from a fatal error.
As for solving this issue, your error is telling you $cakeXml is a non-object. One solution would be to do something like this.
try {
$cakeXml = simplexml_load_string($xml);
if (!is_object($cakeXml)) {
throw new Exception('simplexml_load_string returned non-object');
}
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
DOMXPath methods i.e. xpath or evaluate does not throw exceptions. Hence, you will need to explicitly validate and throw the exception.
See below code snippet:
$xml_1= "";
try {
$cakeXml = simplexml_load_string($xml_1);
if ( !is_object($cakeXml) ) {
throw new Exception(sprintf('Not an object (Object: %s)', var_export($cakeXml, true)));
} else {
$parseSuccess = $cakeXml->xpath('//pages');
print('<pre>');print_r($parseSuccess);
}
} catch (Exception $ex) {
echo 'Caught exception: ', $ex->getMessage(), "\n";
}

Categories