Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of dealing with Error in PHP7

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the way to deal with Error in PHP7". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the way to deal with Error in PHP7".

Some time ago, I encountered a strange situation in the project at that time: using GuzzleHttp to send a curl request, the API response timed out and an exception was thrown. However, catch (\ Exception) did not catch an exception, causing the code to stop running unexpectedly. Later, looking at the data, it was found that in PHP 7, the exception thrown by the GuzzleHttp request timeout inherits Error, while Error does not inherit Exception, so catch (\ Exception) cannot catch and handle the exception.

The treatment of Error in PHP 7

In PHP 5, when a fatal error occurs in the program, the script stops running immediately. Also, error handlers set through set_error_handler are not called in this case.

⒈ Custom error Handler set_error_handler

   set_error_handler accepts two parameters, the first is a custom error handler, and the second parameter specifies the error level that triggers the custom error handler. It is important to note, however, that only one custom error handler can work at any time.

Function func_notice ($num, $str, $file, $line) {print "Encountered notice $num in $file, line $line: $str\ n";} function func_error ($num, $str, $file, $line) {print "Encountered error $num in $file, line $line: $str\ n";} set_error_handler ("func_notice", E_NOTICE); set_error_handler ("func_error", E_ERROR); echo $foo

After the    code is executed, it outputs PHP Notice: Undefined variable: foo. After the second set_error_handler is executed, the custom error handler becomes func_error, and the error level that triggers the custom error handler becomes E_ERROR. In PHP, undefined variables only trigger errors at the E_NOTICE level, so custom error handlers are not triggered.

It should be noted that custom error handlers do not work on the following error levels:

E_ERROR 、 E_PARSE 、 E_CORE_ERROR 、 E_CORE_WARNING 、 E_COMPILE_ERROR 、 E_COMPILE_WARNING 、 E_STRICT

   among the above-mentioned errors that cannot be handled by custom error handlers, all those that end in ERROR are fatal errors. The other ones are not fatal mistakes, but

E_PARSE is an error that occurs when parsing the PHP code. Before the PHP code starts running, the custom error handler cannot handle the error.

E_CORE_WARNING is generated in the initialization startup phase of PHP, when the PHP code is not yet running, so it cannot be handled by a custom error handler

E_COMPILE_WARNING is generated during the compilation phase of PHP code, so it cannot be handled by custom error handlers

As for E_STRICT, which is proposed by PHP to ensure the best interoperability and forward compatibility of the code, it will not be handled by custom error handlers.

Function func_error ($num, $str, $file, $line) {print "Encountered error $num in $file, line $line: $str\ n";} set_error_handler ('func_error', E_NOTICE); $obj =' foo';$obj- > method ()

The code above    runs and outputs the result:

PHP Fatal error: Call to a member function method () on string

Although    sets up a custom error handler, it does not work when a fatal error occurs.

   can log specific error messages by registering a termination callback (shutdown_function) in PHP 5 for fatal errors that cannot be handled by custom error handlers, but it is also limited to recording error messages. The code will still stop running when a fatal error occurs.

ShutdownHandler = function () {print PHP_EOL; print "=". PHP_EOL; print "Running the shutdown handler". PHP_EOL; $error = error_get_last (); if (! empty ($error)) {print "Looks like there was an error:". Print_r ($error, true). PHP_EOL; / / you can add the logic for logging} else {/ / the program runs normally and ends print "Running a normal shutdown without error.". PHP_EOL;}}; register_shutdown_function ($shutdownHandler); $obj = 'foo';$obj- > method ()

The code execution above    will output

PHP Fatal error: Call to a member function method () on string in / home/chenyan/test.php on line 24==Running the shutdown handlerLooks like there was an error: Array ([type] = > 1 [message] = > Call to a member function method () on string [file] = > / home/chenyan/test.php [line] = > 24)

⒉ undo custom error handler

   when you set up multiple custom error handlers at the same time, although only the last set custom error handler works. However, custom error handlers for all settings are saved as a stack (FILO).

   uses restore_error_handler to undo the most recently set custom error handler; if set_error_handler is called multiple times at the same time, the error handler at the top of the stack is undone each time restore_error_handler is called.

Function func_notice ($num, $str, $file, $line) {print "Encountered notice: $str\ n";} set_error_handler ("func_notice", E_NOTICE); echo $foo;set_error_handler ("func_notice", E_NOTICE); echo $foo;restore_error_handler (); echo $foo;restore_error_handler (); echo $foo;restore_error_handler () Echo $foo;restore_error_handler (); echo $foo

If the code above    runs, it will output:

Encountered notice: Undefined variable: fooEncountered notice: Undefined variable: fooPHP Notice: Undefined variable: foo

Error handling in ⒊ PHP 7

   in PHP 7, when a fatal error or an error of type E_RECOVERABLE_ERROR occurs, an Error is usually thrown and the program does not terminate.

Try {$obj = 'foo'; $obj- > method ();} catch (\ Error $e) {echo $e-> getMessage ();}

When    runs the above code, it outputs

Call to a member function method () on string

E_RECOVERABLE_ERROR is a trapable fatal error that does not leave the Zend engine in an unstable state, but must be caught and handled. If left unhandled, this error will eventually become an error of type E_ERROR, eventually causing the PHP code to stop running.

In    php 7, not all fatal errors throw Error, and fatal errors (Out Of Memory) in certain cases can still cause the code to stop running. In addition, if the thrown Error is not captured and processed, the code will still stop running.

/ / the size of bak.sql is 377 M file / PHP configured memory_limit = 128Mtry {$file ='. / bak.sql'; file_get_contents ($file);} catch (\ Error $e) {echo $e-> getMessage () } / / execution of the above code still produces a fatal error PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 395191240 bytes) / / the thrown Error is not captured and processed, and the code will still stop running $obj = 'foo';$obj- > method (); / / execute the above code, because the thrown Error is not captured and processed with try/catch, the program will still stop running PHP Fatal error: Uncaught Error: Call to a member function method () on string

Error in    PHP 7 does not inherit Exception, but does so to prevent code in PHP 5 that captures and processes Exception from capturing these Error. Because in PHP 5, these fatal errors can cause the code to stop running.

Both    Error and Exception inherit from Throwable. In PHP 7, Throwable is an interface, and all objects that can be thrown through the throw keyword implement this interface.

Interface Throwable {public function getMessage (): string; public function getCode (): int; public function getFile (): string; public function getLine (): int; public function getTrace (): array; public function getTraceAsString (): string; public function getPrevious (): Throwable; public function _ toString (): string;}

What    needs to point out is that Throwable is the underlying interface,PHP code of PHP, and Throwable cannot be implemented directly. This restriction is imposed because usually only Error and Exception can be thrown, and the stack trace information they are thrown is also stored in the thrown Error and Exception, which cannot be achieved by the developer's custom class in PHP code.

   to implement Throwable in PHP code must be implemented by inheriting Exception.

Interface CustomThrowable extends Throwable {} class CustomException extends Exception implements CustomThrowable {} throw new CustomException ()

Inheritance relationship between Error and Exception in    PHP 7

Interface Throwable |-Exception implements Throwable |-Other Exception classes |-Error implements Throwable |-TypeError extends Error |-ParseError extends Error |-AssertionError extends Error |-ArithmeticError extends Error |-DivizionByZeroError extends ArithmeticError

TypeError

   throws a TypeError when the data type of the passed parameter or return value of the function is not consistent with the declared data type

Function add (int $left, int $right) {return $left + $right;} try {$value = add ('left',' right');} catch (TypeError $e) {echo $e-> getMessage ();} / / run the above code, you will output: Argument 1 passed to add () must be of the type int, string given

   when strict mode is turned on, TypeError will also be thrown if the number of parameters passed by the PHP built-in function does not match the required parameters.

Declare (strict_types = 1); try {substr ('abc');} catch (TypeError $e) {echo $e-> getMessage ();} / / run the above code, you will output: substr () expects at least 2 parameters, 1 given

   by default, PHP 7 is in weak mode. In weak mode, PHP 7 converts the data type of the passed parameter to the desired data type as much as possible. For example, if the parameter type expected by the function is string, and the actual data type of the parameter is int, then PHP converts int to string.

/ / declare (strict_types = 1); function add (string $left, string $right) {return $left + $right;} try {$value = add (11,22); echo $value;} catch (TypeError $e) {echo $e-> getMessage () } / / if the above code runs, it will output normally. 33. Int → string → int / / but if you change PHP to strict mode, the run will throw TypeErrorArgument 1 passed to add () must be of the type string, int given.

ParseError

   throws a ParseError when there is a syntax error in a file contained in include or require, or a syntax error in the code in the eval () function

/ / a.php$a = 1$ b = 2ax / test.phptry {require 'a.phpause;} catch (ParseError $e) {echo $e-> getMessage ();} / / the above code will output: syntax error, the code in the unexpected' $b'(T_VARIABLE) / / eval function has syntax errors try {eval ("$a = 1");} catch (ParseError $e) {echo $e-> getMessage () } / / the output of the above code is: syntax error, unexpected end of file

AssertionError

Ini_set ('zend_assertions', 1); ini_set (' assert.exception', 1); try {$test = 1; assert ($test = 0);} catch (AssertionError $e) {echo $e-> getMessage ();} / / run the above code to output: assert ($test = 0)

ArithmeticError

   in PHP 7, there are currently two situations in which ArithmeticError is thrown: a bitwise move operation, where the second argument is negative; and using the intdiv () function to calculate the quotient of PHP_INT_MIN and-1 (if you use / calculate the quotient of PHP_INT_MIN and-1, the result is automatically converted to float).

Try {$value = 1 getMessage ();} / run the above code, you will output: Bit shift by negative numbertry {$value = intdiv (PHP_INT_MIN,-1);} catch (ArithmeticError $e) {echo $e-> getMessage ();} / / run the above code, you will output: Division of PHP_INT_MIN by-1 is not an integer

DivisionByZeroError

At present, there are two cases in which    throws DivisionByZeorError: when performing a modular (%) operation, the second Operand is 0; when using intdiv () to calculate the quotient of two numbers, the divisor is 0. If you use / compute the quotient divisor of two numbers to zero, PHP will only produce a Warning. And, if the divisor is not 0, the result is INF, and if the divisor is also 0, the result is NaN.

Try {$value = 1% 0; echo $value;} catch (DivisionByZeroError $e) {echo $e-> getMessage (), "\ n";} / / run the above code, you will output: Modulo by zerotry {$value = intdiv (0,0); echo $value;} catch (DivisionByZeroError $e) {echo $e-> getMessage (), "\ n";} / / run the above code, you will output: Division by zero

   is usually in real business, it is not common to capture and process the thrown Error, because once the thrown Error indicates that there is a serious BUG in the code, it needs to be fixed. Therefore, in the actual business, Error is more often used to capture and record specific error logs, and then notify developers for BUG fixes.

Thank you for your reading, the above is the content of "what is the way to deal with Error in PHP7". After the study of this article, I believe you have a deeper understanding of what is the way to deal with Error in PHP7, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report