Error messages are nightmares to a programmer. Default error messages are annoying and looking ugly. And kind of security threat as well. You probably wish to show a custom message when an error occurred. And tried and failed?
I had written this small code snippet for one of my projects and now wondering if this can help others. This function will triggered when a shutdown event happens.
Place this code at the top of your project file. Or maybe create a separate file and include where required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | /** * Handle error messages in PHP * * @author Nazmul Ahsan <n.mukto@gmail.com> * @link http://nazmulahsan.me/?p=636 */ function na_shutdown() { ini_set( 'display_errors', 1 ); $error_triggered = false; if ( $error = error_get_last() ) { switch( $error['type'] ) { case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: $error_triggered = true; break; } } // if error occurs, set the message if ( $error_triggered ) { // if fatal error if( strpos( strtolower( $error['message'] ), 'fatal error' ) !== false ) { $message = "A fatal error was occured."; } // if undefined function elseif( strpos( strtolower( $error['message'] ), 'undefined function' ) !== false ) { $message = "An undefined function was called."; } // if undefined function elseif( strpos( strtolower( $error['message'] ), 'failed opening required' ) !== false ) { $message = "A required file is missing."; } // other errors else{ $message = "Something is wrong."; } // display the message echo $message; } } register_shutdown_function( 'na_shutdown' ); |
This will help you handle messages for fatal error, undefined function error and required file not found error. And a general message for other errors.
So, when an undefined function is called, for example
1 | some_undefined_function(); |
It’ll show your defined message instead of showing-
1 | PHP Fatal error: Call to undefined function some_undefined_function |
You can change messages in line 27, 31, 35 and 39 with your own texts too.