talentrydev / error-handling
PHP library for converting PHP errors to exceptions
3.0.0
2024-05-31 13:22 UTC
Requires
- php: ^8.3
Requires (Dev)
- phpunit/phpunit: ^11
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-12-01 00:14:45 UTC
README
This library exposes a service that can be used to convert PHP errors to exceptions.
Installing and configuring the symfony bundle
- Run:
composer require talentrydev/error-handling
Usage
- Get an ErrorHandler instance from the ErrorHandlerFactory
- Call
startHandling()
to start handling errors. You can add as many or as fewSeverity
arguments (however at least one is required). - Execute the code that you expect will throw errors in a try-catch block, catching the appropriate
Throwable
(see table below). - Call
stopHandling()
to prevent errors being converted to exceptions in other places.
Example
<?php
use Talentry\ErrorHandling\Enum\Severity;
use Talentry\ErrorHandling\Error\Warning;
use Talentry\ErrorHandling\ErrorHandler;
class MyClass
{
public function __construct(
private readonly ErrorHandler $errorHandler,
) {
}
public function callBadlyWrittenLibrary()
{
try {
$this->errorHandler->startHandling(new Severity(Severity::WARNING)));
BadlyWrittenLibrary::methodThatTriggersWarnings();
} catch (Warning $warning) {
//log or ignore or do whatever you think is appropriate
} finally {
$this->errorHandler->stopHandling();
}
}
}
Available Severity types
According to the PHP manual:
The following error types cannot be handled with a user defined function:
E_ERROR
,E_PARSE
,E_CORE_ERROR
,E_CORE_WARNING
,E_COMPILE_ERROR
,E_COMPILE_WARNING
, and most ofE_STRICT
raised in the file where set_error_handler() is called.
Therefore, this module provides support only for the following Severity types:
Severity | PHP Error Level | Thrown Throwable |
---|---|---|
WARNING | E_WARNING | Warning |
NOTICE | E_NOTICE | Notice |
USER_ERROR | E_USER_ERROR | UserError |
USER_WARNING | E_USER_WARNING | UserWarning |
USER_NOTICE | E_USER_NOTICE | UserNotice |
STRICT | E_STRICT | Strict |
RECOVERABLE_ERROR | E_RECOVERABLE_ERROR | RecoverableError |
DEPRECATED | E_DEPRECATED | Deprecated |
USER_DEPRECATED | E_USER_DEPRECATED | UserDeprecated |
UNKNOWN | None | UnknownError |
The special UNKNOWN
Severity is provided as a fallback mechanism in case an unrecognized error code is caught.
Do not rely on it or use it directly.