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>"; }