This article mainly introduces the example of php exception handling. the code illustrates how to capture and handle common and fatal errors. For more information, see
The code is as follows:
// Disable error output
Error_reporting (0 );
// Set the Error Processor
Set_error_handler ('errorhandler ');
Register_shutdown_function ('fatalerrorhandler ');
Class Test {
Public function index (){
// Here, a warning error occurs, starting with errorHandler.
Echo $ undefinedVarible;
}
}
Function errorHandler ($ errno, $ errstr, $ errfile, $ errline ){
$ Arr = array (
'['. Date ('Y-m-d h-I-s'). ']',
'Http: // www.baidu.com ',
'| ',
$ Errstr,
$ Errfile,
'Line: '. $ errline,
);
// Write error logs
// Format: time uri | the row where the error message file is located
Error_log (implode ('', $ arr)." \ r \ n ", 3, './test.txt', 'Extra ');
Echo implode ('', $ arr)." \ r \ n ";
}
// Catch fatalError
Function fatalErrorHandler (){
$ E = error_get_last ();
Switch ($ e ['type']) {
Case E_ERROR:
Case E_PARSE:
Case E_CORE_ERROR:
Case E_COMPILE_ERROR:
Case E_USER_ERROR:
ErrorHandler ($ e ['type'], $ e ['message'], $ e ['file'], $ e ['line']);
Break;
}
}
$ Test = new Test ();
//// A warning error occurs, which is captured by errorHandler.
$ Test-> index ();
// A fatal error occurs. if the script stops running, fatalErrorHandler is triggered.
$ Test = new Tesdt ();
$ Test-> index ();