vudaltsov/exceptionally

轻松将错误转换为异常

0.1.0 2019-08-03 02:04 UTC

This package is auto-updated.

Last update: 2024-08-29 05:27:29 UTC


README

A PHP库,可以轻松将错误转换为异常。

<?php

use function VUdaltsov\Exceptionally\exceptionallyCall;
use VUdaltsov\Exceptionally\Exception\WarningException;

try {
    $handle = exceptionallyCall('fopen', 'data.xml', 'rb');
} catch (WarningException $exception) {
    throw new FailedToOpenFileException($exception->getMessage(), 0, $exception);
}

安装

composer require vudaltsov/exceptionally

用法

exceptionallyCall()

函数exceptionallyCall(callable $callable, mixed ...args): mixed允许立即执行可调用对象。

<?php

use function VUdaltsov\Exceptionally\exceptionallyCall;
use VUdaltsov\Exceptionally\Exception\WarningException;

try {
    $file = 'data.xml';
    $handle = exceptionallyCall('touch', $file);
} catch (WarningException $exception) {
    throw new FailedToTouchFileException($file, 0, $exception);
}

exceptionally()

在复杂情况下,使用函数exceptionally(): Exceptionally。它返回一个不可变的配置器。

例如,您可以指定错误严重级别(有关详细信息,请参阅set_error_handler(..., $error_types))。默认情况下,捕获所有错误(E_ALL)。

<?php

use function VUdaltsov\Exceptionally\exceptionally;
use VUdaltsov\Exceptionally\Exception\NoticeException;

$accessor = exceptionally()
    ->callable(static function (array $array, string $offset): string {
        return $array[$offset];
    })
    ->level(E_NOTICE)
;

try {
    $value = $accessor(['a' => 1], 'b');
} catch (NoticeException $exception) {
    throw new OutOfRangeException($exception->getMessage(), 0, $exception);
}

您甚至可以设置默认参数。

<?php

use function VUdaltsov\Exceptionally\exceptionally;

$mkdir = exceptionally()
    ->callable('mkdir')
    ->args(__DIR__.'/a', 0777, true)
;

$mkdir();

默认情况下,抑制的错误不会抛出,但您可以启用该功能。

<?php

use function VUdaltsov\Exceptionally\exceptionally;

exceptionally()
    ->throwSuppressed()
    ->callable(static function (): void {
        @include __DIR__.'/script.php';
    })
    ->call()
;

不可变性

exceptionally()配置器是不可变的。每次调用都会返回一个新的对象(类似于PSR-7消息)。因此,您可以在代码中安全地重用预先配置的实例。

异常

exceptionally抛出原生的ErrorException子类的异常。

请注意,E_ERRORE_PARSEE_CORE_ERRORE_CORE_WARNINGE_COMPILE_ERRORE_COMPILE_WARNING级别不受支持,因为它们不能用set_error_handler函数处理。

E_STRICT也不受支持,因为它不再在PHP 7中使用