An example of php custom error handling function code

WBOY
Release: 2016-07-25 09:00:02
Original
1180 people have browsed it
  1. function myErrorHandler($errno, $errstr, $errfile, $errline){

  2. if(!(error_reporting() &$errno)){return;}
  3. switch ($errno){
  4. case E_USER_ERROR:
  5. echo "My ERROR [$errno] $errstr
    ";
  6. echo "错误行:$errline 在文件:$errfile之中
    ";
  7. echo " PHP版本: " .PHP_VERSION ." (" .PHP_OS .")
    ";
  8. break;
  9. case E_USER_WARNING:
  10. echo "My WARNING [$errno] $errstr
    ";
  11. break;
  12. case E_USER_NOTICE:
  13. echo "My NOTICE [$errno] $errstr
    ";
  14. break;
  15. default:
  16. echo "Unknown error type: [$errno] $errstr
    ";
  17. break;
  18. }
  19. return true;
  20. }

  21. function trigger_test($age){//抛出错误的测试函数

  22. if($age <= 0 || $age > 999) trigger_error("年龄不合法:$age岁", E_USER_ERROR);
  23. if($age < 18) trigger_error("未成年:$age岁", E_USER_WARNING);
  24. if($age > 40 && $age < 100) trigger_error("年龄稍大:$age岁", E_USER_NOTICE);
  25. }
  26. //如果只是简单统一地处理错误:
  27. $errorHandler = set_error_handler("myErrorHandler");
  28. trigger_test(1000);//会抛出一个error级的错误

  29. function myError($errno, $errstr, $errfile, $errline){
  30. print_r(func_get_args());
  31. //具体处理方法
  32. }
  33. function myWarning($errno, $errstr, $errfile, $errline){
  34. print_r(func_get_args());
  35. //具体处理方法
  36. }

  37. function myNtice($errno, $errstr, $errfile, $errline){

  38. print_r(func_get_args());
  39. //具体处理方法
  40. //by http://bbs.it-home.org
  41. }

  42. //如果要分别处理不同错误级别:

  43. set_error_handler('myError',E_USER_ERROR);
  44. set_exception_handler('myWarning',E_USER_WARNING);
  45. set_exception_handler('myNtice',E_USER_NOTICE);
  46. trigger_error('故意抛出个错误,还是很严重的哪一种!',E_USER_ERROR);

复制代码

有关trigger_error的介绍,请参考php手册中:http://bbs.it-home.org/shouce/php5/function.trigger-error.html 这部分的内容。



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!