I would like to share with you a php exception handling program. The function is very simple. When a major error occurs, you can write logs and prompt users with a friendly reminder. It is very useful, right?
I would like to share with you a php exception handling program. The function is very simple. When a major error occurs, you can write logs and prompt users with a friendly reminder. It is very useful, right?
Directly Add code
<? Php // exceptionHandle. php xiecongwen 20140620 // define ('debug', true);/*** Display all errors when APPLICATION_ENV is development. */if (defined ('debug') {error_reporting (E_ALL); ini_set ("display_errors", 1);} if (! Defined ('debug') {/*** when a major error occurs, write the log and kindly prompt the user * (PS: write the code here only because it is registered elsewhere, the configuration function cannot be called when a problem occurs. to be improved ...) */function shutdownHandler () {/*** write the log directly in the root directory shutdownlog.txt */$ lasterror = error_get_last (); if ($ lasterror) {$ error = strval (date ("Y-m-d h: I: s ")). '=> '. "[SHUTDOWN] lvl :". $ lasterror ['type']. "| msg :". $ lasterror ['message']. "| file :". $ lasterror ['file']. "| ln :". $ lasterror ['line']. "\ n"; file_put_co Ntents ('. /log /'. date ("Ymd" 2.16.'shutdownlog.txt ', $ error, FILE_APPEND); // friendly prompt for user ob_end_clean (); die ('Sorry, I have an error! ') ;}} Register_shutdown_function ('shutdownhandler');} if (! Defined ('debug') {function errorHandler ($ errno, $ errstr = '', $ errfile ='', $ errline = 0) {// write logs $ exception = new \ ErrorException ($ errstr, 0, $ errno, $ errfile, $ errline ); $ msg = strval (date ("Y-m-d h: I: s ")). '=> '. 'Type :'. getErrTypeName ($ errno ). ''. getMsg ($ exception); file_put_contents ('. /log /'. date ("Ymd" 2.16.'error.txt ', $ msg, FILE_APPEND); switch ($ errno) {case E_NOTICE: return; case E_DEPRECATED: return;} throw $ Exception;} function getErrTypeName ($ errno) {switch ($ errno) {case E_NOTICE: return 'e _ NOTICE '; case E_DEPRECATED: return 'e _ deprecated'; default: return $ errno;} function exceptionHandler ($ ex) {$ msg = strval (date ("Y-m-d h: I: s ")). '=> '. getMsg ($ ex); file_put_contents ('. /log /'. date ("Ymd" 2.16.'exception.txt ', $ msg, FILE_APPEND);} function getMsg ($ exception) {// get the most accurate exception while ($ exception-> getPrevious ()) $ exception = $ Exception-> getPrevious (); $ msg = 'message :'. $ exception-> getMessage (); $ msg. = 'file :'. $ exception-> getFile (). ':'. $ exception-> getLine (). "\ n"; return $ msg;} set_error_handler ('errorhandler', E_ALL); set_exception_handler ('exceptionhandler');}?>
,