mpyw/exceper

Provides temporary error handler automatically using set_error_handler() and restore_error_handler().

v2.0.0 2021-06-24 18:51 UTC

This package is auto-updated.

Last update: 2024-04-13 07:01:18 UTC


README

Provides temporary error handler automatically using set_error_handler() and restore_error_handler().

PHP Feature Restriction
5.3.2~ 😄 Supported
~5.3.1 💥 Incompatible

Installing

composer require mpyw/exceper

Quick Example

<?php

require __DIR__ . '/vendor/autoload.php';

use Mpyw\Exceper\Convert;

try {

    // We pick errors triggered by fopen() or fgets().
    // They are converted into \RuntimeException.
    Convert::toRuntimeException(function () {
        $fp = fopen('http://example.com', 'rb');
        while (false !== $line = fgets($fp)) {
            echo $line;
        }
    });

} catch (\RuntimeException $e) {

    // Do something here

}

// Error handler is already automatically restored.

API

Mpyw\Exceper\Convert::to()
Mpyw\Exceper\Convert::to{$class}()

Capture errors to convert into an instance of the specified class.

  • Error handlers are automatically restored.
  • ->getFile() and ->getLine() returns correct locations like ErrorException does.
static Mpyw\Exceper\Convert::to(string $class, callable $callback, int $types = E_ALL | E_STRICT): mixed
static Mpyw\Exceper\Convert::to{$class}(callable $callback, int $types = E_ALL | E_STRICT): mixed
static Mpyw\Exceper\Convert::to(string $class, int $code, callable $callback, int $types = E_ALL | E_STRICT): mixed
static Mpyw\Exceper\Convert::to{$class}(int $code, callable $callback, int $types = E_ALL | E_STRICT): mixed

Arguments

  • (string) $class
    Conversion target class name which is an instance of \Exception or \Throwable. Please note that case-sensitivity of class name depends on the implementation of your autoloaders, which can cause an unexpected behavior if the target class is not loaded.
  • (int) $code
    Error code passed to the constructor as the second argument. Default to 0.
  • (callable) $callback
    Callback function to be executed. This parameter SHOULD be used as \Closure because arguments cannot be specified.
  • (int) $types
    Bit mask of target error severities.

Return Value

(mixed)
Propagates upcoming value from $callback().

Exception

Converted errors.

Mpyw\Exceper\Convert::silent()

Capture errors but never throw anything.

static Mpyw\Exceper\Convert::silent(callable $callback, int $types = E_ALL | E_STRICT, bool $captureExceptions = true): mixed

Arguments

  • (callable) $callback
    Callback function to be executed. This parameter SHOULD be a \Closure because arguments cannot be specified.
  • (int) $types
    Bit mask of target error severities.
  • (bool) $captureExceptions
    Capture exceptions that were directly thrown; not originated in set_error_handler().

Return Value

(mixed)
Propagates upcoming value from $callback(). Returns null if something thrown.