PHP custom error handling
Under normal circumstances, php will output the fatal error directly, and output the error source (file address, row number) and cause, so that the development can easily locate the problem.
However, sometimes. if the information is not output due to ini settings or third-party framework configuration problems, you must set relevant parameters and output the error information to help you quickly locate the problem.
Error_reporting is a global configuration parameter in php. ini. Used to configure the error output level. It can be used to set the error output level.
Error_reporting (int $ level). When $ level is 0, the error output is disabled, that is, no error is output.
Set_error_handler
The default error handling method of php is to output messages. However, if you need to define other operations, you need to customize the error handler function.
Php provides the built-in function set_error_handler to help us register our own error handling functions. The function prototype is as follows:
Mixed set_error_handler (callback $ error_handler [, int $ error_types = E_ALL | E_STRICT])
It is worth noting that even if an error handler is registered, the default behavior will still be executed, that is, when an error occurs, the error message will still be output, therefore, you need to set the error level to 0 in the program, and then register your own error handling function. This method is especially important in the production environment, because even if an error occurs, sensitive internal error messages are not exposed to potential malicious users. It is also important to note that custom error handling functions cannot handle fatal errors (such as compilation errors ).
The following is a column using a custom error handler:
<?phperror_reporting(0);function error_handler($error_level, $error_message, $file, $line) { $exit = false; switch ($error_level) { case E_NOTICE: case E_USER_NOTICE: $error_type = 'Notice'; break; case E_WARNING: case E_USER_WARNING: $error_type = 'Warning'; break; case E_ERROR: case E_USER_ERROR: $error_type = 'Fatal Error'; $exit = true; break; default: $error_type = 'Unknown'; $exit = true; break; } printf("%s: %s in %s on line %d\n", $error_type, $error_message, $file, $line); if ($exit) { die(); }}set_error_handler('error_handler');
Echo $ novar;
Echo 3/0;
Trigger_error ('trigger a fatal error', E_USER_ERROR );
New NonExist ();
Run this script to get the following output:
Notice: Undefined variable: novar in/your/php_demo_file.php on line 40
Warning: Division by zero in/your/php_demo_file.php on line 41
Fatal Error: Trigger a fatal error in/your/php_demo_file.php on line 42
We can see that the last "new NoExistClass ()" exception is not captured by the custom error handler function.
Finally, the handler mentions that set_exception_handler registers the top-layer Exception Handling. In the web application, you can set it and then jump to the error handling page in a unified manner.