PHP Global Exception Handler

Code Snippets Global Exception Handler
Share:

About

In this code snippet, we’ll make a global exception handler in PHP.

A global exception handler is used to catch any unhandled exception that might bubble up in your code. This way you can log the exception and let the user know there was an error instead of the program just crashing.

Let’s see how to implement it in the example below.

Code:

index.php
<?php
//Include needed files./////////////
require_once(dirname(__FILE__) . "\displayData.php");
require_once(dirname(__FILE__) . "\getData.php");
//Entry point///////////////////////
set_exception_handler(function ($ex) {
//Get error message.
$errorMessage = "An error occured in ". $ex->getFile() ." on line ". $ex->getLine() ." Error message: ". $ex->getMessage();
//Use some kind of error logging to save the error info. 
//logError($errorMessage);
//Let the user know something went worong nicely without crashing the app.
echo "An error occurred please refresh the website or try again later.";
//Exit program execution.
exit();
});
runProgram();
//Code//////////////////////////////
function runProgram(){
$data = GetData();
DisplayData($data);
}
getData.php
<?php
function GetData(){
//A wild unhandled exception appears ...
throw Exception("I'm an unhandled exception!");
return "Data from DB ...";
}
displayData.php
<?php
function DisplayData($data){
echo $data;
echo "<br>";
}

Resulting Output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger