internations/exception-bundle

帮助您将 Symfony Bundle 打造成为优秀的异常公民。是的,它有明确的观点。

5.3.0 2020-06-16 09:51 UTC

README

Build Status

为您的 Symfony 2 bundles 提供干净的异常处理

ExceptionBundle 帮助您管理 bundle 的异常

  • 从命令行生成异常子类,包括一个标记接口
  • 将一个 bundle 中的所有全局 throw 语句替换为 bundle 特定的异常类

为什么你应该关心呢?

  • 异常越简单,类型区分越简单,异常条件处理就越简单
  • 通过提供一个标记接口,所有 bundle 异常类都实现,允许客户端显著简化异常处理
  • 通常,手动创建所有异常子类是繁琐的,ExceptionBundle 可以帮到您

使用方法

生成 bundle 特定的异常子类

此命令将生成一系列异常

php app/console exception:generate app/src/MyVendor/MyBundle "MyVendor\MyBundle" ExceptionInterface RuntimeException DomainException

ls app/src/MyVendor/MyBundle/Exception

ExceptionInterface.php  RuntimeException.php  DomainException.php

cat app/src/MyVendor/MyBundle/Exception/RuntimeException.php

<?php
namespace MyVendor\MyBundle\Exception;

use RuntimeException as BaseRuntimeException;

class RuntimeException extends BaseRuntimeException implements ExceptionInterface
{
}

您还可以指定快捷方式 "spl" 来子类化所有 Spl 异常

重写 bundle 异常

ExceptionBundle 使用 PHP 解析器重写 bundle 代码库中的所有 throw 语句。

cat app/src/MyVendor/MyBundle/MyClass.php

<?php
namespace MyVendor\MyBundle;

use RuntimeException;
...
    throw new RuntimeException('Runtime error');
...
    throw new \InvalidArgumentException('Invalid argument');

php app/console exception:rewrite app/src/MyVendor/MyBundle "MyVendor\MyBundle"

将代码重写为

<?php
namespace MyVendor\MyBundle;

use MyVendor\MyBundle\Exception\InvalidArgumentException;
use MyVendor\MyBundle\Exception\RuntimeException;
...
    throw new RuntimeException('Runtime error');
...
    throw new InvalidArgumentException('Invalid argument');
...

安装

internations/exception-bundle 添加到您的 composer.json,并像这样编辑 AppKernel.php

<?php
...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            ...
        );

        if ($this->debug) {
            $bundles[] = new InterNations\Bundle\ExceptionBundle\InterNationsExceptionBundle();
        }
    }
}