Code Modernization: Fix trigger_error() with E_USER_ERROR deprecation in wp_trigger_error().
PHP 8.4 deprecates the use of trigger_errror()
with E_USER_ERROR
as the error level, as there are a number of gotchas to this way of creating a Fatal Error
(finally
blocks not executing, destructors not executing). The recommended replacements are either to use exceptions or to do a hard exit
.
WP has its own wp_trigger_error()
function, which under the hood calls trigger_error()
. If passed E_USER_ERROR
as the $error_level
, this will hit the PHP 8.4 deprecation.
Now, there were basically three options:
- Silence the deprecation until PHP 9.0 and delay properly solving this until then. This would lead to an awkward solution, as prior to PHP 8.0, error silencing would apply to all errors, while, as of PHP 8.0, it will no longer apply to fatal errors. It also would only buy us some time and wouldn't actually solve anything.
- Use
exit($status)
when wp_trigger_error()
is called with E_USER_ERROR
. This would make the code untestable and would disable handling of these errors via custom error handlers, which makes this an undesirable solution.
- Throw an exception when
wp_trigger_error()
is called with E_USER_ERROR
. This makes for the most elegant solution with the least BC-breaking impact, though it does open it up to the error potential being "caught" via a try-catch
. That's not actually a bad thing and is likely to only happen for those errors which can be worked around, in which case, it's a bonus that that's now possible.
The third option is implemented which:
- Introduces a new
WP_Exception
class.
- Starts using
WP_Exception
in the wp_trigger_error()
function when the $error_level
is set to E_USER_ERROR
.
This change is covered by pre-existing tests, which have been updated to expect the exception instead of a PHP error.
Why not use WP_Error
?
Well, for one, this would lead to completely different behaviour (BC).
As WP_Error
doesn't extend Exception
, the program would not be stopped, but would continue running, which would be a much bigger breaking change and carries security risks. WP_Error
also doesn't natively trigger displaying/logging of the error message, so in that case, it would still need an exit
with the error message, bringing us back to point 2 above.
Introducing WP_Exception
provides (essentially) the same behaviour in that it retains the fatal error and error message displaying/logging behaviors. It also introduces a base Exception class, from which future exception classes can extend.
References:
Follow-up to [56530].
Props jrf, hellofromTonya.
See #62061.