PHP的全局错误处理详解_PHP
本文目的
PHP的全局错误处理,在开发项目的时候很有用,可以帮助开发者快速定位一些问题,提高工作效率。默认情况下,全局错误会直接输出,但是最近开发时使用的一个框架库对全局错误处理进行了设定,导致很多错误信息没有输出,在定位问题上有一定的耗时。所以,研究了一下此库的实现,发现它设定了error_reporting和set_error_handler,导致此现象。现在记录一下这两个函数的用法,作为备忘录。
背景
PHP没有类型检测,开发人员比较容易输入错误单词,引起致命错误,最终导致脚本停止执行。如果这个时候,没有得到任何错误消息,那么会是一件很痛苦的事情。你不得不从脚本的第一行代码开始调试,在成千上万行的代码中不断的print或者echo,直到定位到这个输错的单词。然后,有不得不原路返回,将先前添加的print或echo全部删除。这时一件及其枯燥乏味的工作。
一般情况
正常情况下,php会将致命错误直接输出,会将错误的出处(文件地址,行号)和原因等输出,这样,开发着可以很方便的定位到问题。
但是有些时候,可能由于php.ini的设置问题,可能是第三方框架配置的问题,导致这些信息没有输出,那么此时,必须学会自己设置相关参数,输出这些错误信息,帮助快速定位问题。
error_reporting
error_reporting是一个php的全局配置参数,在php.ini中。用于配置错误输出级别,参数是比特位,可以用来设置错误输出的级别,下面是从php.ini中copy出来的信息:
; error_reporting is a bit-field. Or each number up to get desired error ; reporting level ; E_ALL - All errors and warnings (doesn't include E_STRICT) ; E_ERROR - fatal run-time errors ; E_RECOVERABLE_ERROR - almost fatal run-time errors ; E_WARNING - run-time warnings (non-fatal errors) ; E_PARSE - compile-time parse errors ; E_NOTICE - run-time notices (these are warnings which often result ; from a bug in your code, but it's possible that it was ; intentional (e.g., using an uninitialized variable and ; relying on the fact it's automatically initialized to an ; empty string) ; E_STRICT - run-time notices, enable to have PHP suggest changes ; to your code which will ensure the best interoperability ; and forward compatibility of your code ; E_CORE_ERROR - fatal errors that occur during PHP's initial startup ; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's ; initial startup ; E_COMPILE_ERROR - fatal compile-time errors ; E_COMPILE_WARNING - compile-time warnings (non-fatal errors) ; E_USER_ERROR - user-generated error message ; E_USER_WARNING - user-generated warning message ; E_USER_NOTICE - user-generated notice message ; ; Examples: ; ; - Show all errors, except for notices and coding standards warnings ; ;error_reporting = E_ALL & ~E_NOTICE ; ; - Show all errors, except for notices ; ;error_reporting = E_ALL & ~E_NOTICE | E_STRICT ; ; - Show only errors ; ;error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR ; ; - Show all errors except for notices and coding standards warnings ; error_reporting = E_ALL & ~E_NOTICE
默认情况下,php会输出所有错误信息,除了notice。同样,php标准函数中提供了名称相同的函数error_reporting(int $level),用于在php脚本中,完成同样的功能。这样将不会影响其他程序。值得注意的是,$level为0的时候是关闭错误输出,也就是任何错误都不会输出。
set_error_handler
php的默认错误处理是将消息输出。但是,有时候需要定义一些其他操作,这时就需要自定义错误处理函数。php提供内置函数set_error_handler可以帮助我们注册自己的错误处理函数。函数原型如下:
mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )
值得注意的是,即使注册了错误处理函数,默认的行为仍然会执行,也就是错误出现时,仍然会输出错误信息,所以需要在程序中显示的将错误级别设置为0,然后在注册自己的的错误处理函数。这种方式,在生产环境下,尤其重要,因为即时出错,敏感内部错误信息也不会暴露给潜在的恶意用户。还有很重要的一点需要指出,自定义错误处理函数不能处理fatal error(比如编译错误)。下面是一个使用自定义错误处理函数的列子:
<?php error_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'); //new NonExist(); echo $novar; echo 3/0; trigger_error ('Trigger a fatal error', E_USER_ERROR); new NonExist(); ?>
执行此脚本可以得到下面的输出:
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
可以看到,最后的“new NoExistClass()”的异常,没有被自定义的错误处理函数捕获。
最后,捎带提一下,set_exception_handler注册顶层的异常处理,在web一用中,可以设定一下,然后统一的跳转到错误处理页面。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP is a widely used server-side programming language that provides powerful and dynamic capabilities to websites. However, in practice, developers may encounter a wide variety of errors and exceptions. One of the common errors is PHPFatalerror:Uncaughtexception'Exception'. In this article, we will explore the causes of this error and how to fix it. The concept of exception In PHP, exception refers to the unexpected situation encountered during the running process of the program, resulting in

PHP exception handling tips: How to use try...catch blocks to catch and handle multiple exceptions Introduction: In PHP application development, exception handling is a very important part. When an error or exception occurs in the code, reasonable exception handling can improve the robustness and reliability of the program. This article will introduce how to use the try...catch block to capture and handle multiple exceptions, helping developers perform more flexible and efficient exception handling. Introduction to Exception HandlingExceptions refer to errors or special situations that occur when a program is running. When an exception occurs

When writing PHP code, exception handling is an integral part of making the code more robust and maintainable. However, exception handling also needs to be used with caution, otherwise it may cause more problems. In this article, I will share some best practices for exception classification in PHP programs to help you make better use of exception handling to improve code quality. The concept of exception In PHP, exception refers to an error or unexpected situation that occurs when the program is running. Typically, exceptions cause the program to stop running and output an exception message.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

How to use PHP's exception handling and fault tolerance mechanism? Introduction: In PHP programming, exception handling and fault tolerance mechanisms are very important. When errors or exceptions occur during code execution, exception handling can be used to capture and handle these errors to ensure program stability and reliability. This article will introduce how to use PHP's exception handling and fault tolerance mechanism. 1. Basic knowledge of exception handling: What is an exception? Exceptions are errors or abnormal conditions that occur during code execution, including syntax errors, runtime errors, logic errors, etc. When different

How to implement global exception handling in PHP backend function development? In PHP back-end development, exception handling is a very important part. It can help us catch errors in the program and handle them appropriately, thereby improving system stability and performance. This article will introduce how to implement global exception handling in PHP back-end function development and provide corresponding code examples. PHP provides an exception handling mechanism. We can catch exceptions and handle them accordingly through the try and catch keywords. Global exception handling refers to all

As the use of APIs becomes more and more widespread, we also need to consider data exception and error handling strategies during the development and use of APIs. This article will explore how PHP handles these issues when implementing APIs. 1. Handling data anomalies There may be many reasons for data anomalies, such as user input errors, network transmission errors, internal server errors, etc. When developing in PHP, we can use the following methods to handle data exceptions. Return the appropriate HTTP status code. The HTTP protocol defines many status codes that can help us

PHP time processing exception: error in returning time, specific code examples are needed. In web development, time processing is a very common requirement. As a commonly used server-side scripting language, PHP provides a wealth of time processing functions and methods. However, in practical applications, sometimes you encounter abnormal situations where the return time is wrong, which may be caused by errors in the code or improper use. In this article, we will introduce some common situations that may cause return time errors and provide some specific code examples to help readers better understand
