talentrydev/error-handling

PHP library for converting PHP errors to exceptions

2.1.0 2021-03-16 11:09 UTC

This package is auto-updated.

Last update: 2024-05-16 18:25:56 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 few Severity 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
{
    /**
     * @var ErrorHandler
     */
    private $errorHandler;

    public function __construct(ErrorHandler $errorHandler)
    {
        $this->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 of E_STRICT raised in the file where set_error_handler() is called.

Therefore, this module provides support only for the following Severity types:

SeverityPHP Error LevelThrown Throwable
WARNINGE_WARNINGWarning
NOTICEE_NOTICENotice
USER_ERRORE_USER_ERRORUserError
USER_WARNINGE_USER_WARNINGUserWarning
USER_NOTICEE_USER_NOTICEUserNotice
STRICTE_STRICTStrict
RECOVERABLE_ERRORE_RECOVERABLE_ERRORRecoverableError
DEPRECATEDE_DEPRECATEDDeprecated
USER_DEPRECATEDE_USER_DEPRECATEDUserDeprecated
UNKNOWNNoneUnknownError

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.