hgh / exception-handler
此软件包集中处理项目的异常行为。该软件包的职责是防止向用户显示不想要的异常。
v1.1.0
2020-07-14 20:17 UTC
Requires
- hgh/helpers: ^1.0
This package is auto-updated.
Last update: 2024-09-15 05:34:17 UTC
README
此软件包集中处理项目的异常行为。该软件包的职责是防止向用户显示不想要的异常。实际上,有时您也想要在输出中显示某些异常。此软件包将处理这两方面。所有异常都可以使用预定义的接口。
目录
安装
要安装此软件包,请通过composer要求。
composer require hgh/exception-handler
接口
有11个接口,异常可以从中实现。实现这些接口的异常将被按类型记录在文件中。
如何使用
异常处理
首先,我们定义一个异常类作为示例。
/** * Class SampleException */ class SampleException extends BaseException implements ShouldPublish, ErrorInterface { } $exception = new SampleException("SampleException");
您可以直接使用异常处理器。
$exceptionHandler = new ExceptionHandler($exception); $exception = $exceptionHandler->handle(); // The result will be SampleException class
或使用外观
\HGh\Handlers\Exception\Facades\Exception::handle($exception); // The result will be SampleException class
如您所见,异常处理的结果是相同的异常,因为它实现了ShouldPublish接口。
让我们定义另一个异常以查看另一种类型的异常处理
/** * Class AnotherSampleException */ class AnotherSampleException extends BaseException implements WarningInterface { } $exception = new AnotherSampleException("AnotherSampleException"); $exception = \HGh\Handlers\Exception\Facades\Exception::handle($exception); // The result will UnexpectedException
看,异常处理的结果不同。它是UnexpectedException,因为它没有实现ShouldPublish接口。
异常日志记录
这里还有一个类用于记录异常。首先在更改异常类型之前,通过ExceptionHandler记录异常,然后通过ExceptionHanlder处理它。
让我们定义一个异常。
/** * Class SampleException */ class SampleException extends BaseException implements ShouldPublish, ErrorInterface { } $exception = new SampleException("SampleException");
现在轮到记录器了。您可以使用以下直接服务
use HGh\Handlers\Exception\Services\ExceptionLogger;$filePath = "/tmp/logs"; $exceptionLogger = new ExceptionLogger($filePath); $exceptionLogger->log($exception);
或使用外观
\HGh\Handlers\Exception\Facades\Exception::log($exception, $filePath);
然后处理它并将其传递到输出。基本上,最好是扩展软件包的外观并定义自己的fileWriter,以防止每次都定义fileWriter。
/** * This class is a facade to all exception actions * PHP version >= 7.0 * * @category Facades * @package ExceptionHandler * @author Hamed Ghasempour <hamedghasempour@gmail.com> * @license MIT https://open-source.org.cn/licenses/MIT * @link null */ class Exception extends ExceptionFacade { /** * This method will log an exception * * @param Throwable $throwable The throwable * @param string $filePath The file path that throwable should be log into * * @return void */ public static function log(Throwable $throwable, string $filePath = null) { if (empty($filePath)) { $filePath = "/tmp/logs"; } parent::log($throwable, $filePath); } }
通过这种方式,在通过异常处理器更改异常之前,您将记录每个异常,您将永远不会错过它们,另一方面,在处理异常之后,您将永远不会向用户显示不想要的异常。