如何在symfony2上添加自定义异常

Kyo*_*ima 9 php symfony

我是Symfony的新手(使用2.2版)并尝试添加自定义异常监听器.我已阅读以下链接但无法使其工作.

我要做的是创建一个自定义的错误异常侦听器,并从我的控制器和服务中使用它,

throw new jsonErrorException('invalid_params');
Run Code Online (Sandbox Code Playgroud)

像这样显示json twig模板.(我正在为我的原生智能手机应用程序开发一个后台程序)

{"status": "error", "message": "invalid_params"}
Run Code Online (Sandbox Code Playgroud)

我已将我的CustomEventListener注册到我的src/My/Bundle/Resources/config/services.yml并创建了一个自定义异常类,如下面的链接所示(覆盖Symfony 2异常?)但我收到错误

symfony exceptions must be valid objects derived from the exception base class
Run Code Online (Sandbox Code Playgroud)

我在这里做错了吗?谢谢.

Pau*_*lla 24

您可以创建自定义异常"symfony方式"让我们看一下异常或在symfony中创建的异常:

首先创建customExceptionInterface

namespace My\SymfonyBundle\Exception;
/**
 * Interface for my bundle exceptions.
 */
interface MySymfonyBundleExceptionInterface
{
}
Run Code Online (Sandbox Code Playgroud)

并创造你的 jsonErrorException

namespace My\SymfonyBundle\Exception;

class HttpException extends \Exception implements MySymfonyBundleExceptionInterface
{
}
Run Code Online (Sandbox Code Playgroud)

不要犹豫,在github上浏览symfony的异常代码示例


aal*_*aap 5

我最近以以下方式在我的Symfony2服务中实现了自定义异常:

MemberAlreadyExistsException.php

<?php

namespace Aalaap\MyAppBundle\Services\Membership;

class MemberAlreadyExistsException extends \Exception
{

}
Run Code Online (Sandbox Code Playgroud)

Subscriber.php

<?php

namespace Aalaap\MyAppBundle\Services\Membership;
...
throw new MemberAlreadyExistsException(
    'The member you are trying to subscribe already'
    . ' exists in this list.'
);
...
Run Code Online (Sandbox Code Playgroud)