Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom exception on symfony2

Tags:

php

symfony

I am new to Symfony(using version 2.2) and trying to add a custom exception listener. I have read the following links but cannot get it to work.

  • Overriding Symfony 2 exceptions?
  • Symfony2 Custom Error Exception Listener - Rendering templates or passing to a controller

What I'm trying to do is to create a custom Error Exception Listener and use it from my controllers and services like this,

throw new jsonErrorException('invalid_params');

to display json twig template like this.(I'm developing a background program for my native smartphone applications)

{"status": "error", "message": "invalid_params"}

I have registered my CustomEventListener to my src/My/Bundle/Resources/config/services.yml and created a custom exception class as shown on following link(Overriding Symfony 2 exceptions?) but I get the error

symfony exceptions must be valid objects derived from the exception base class

Am I doing something wrong here? Thanks.

like image 911
Kyosuke Nakajima Avatar asked Apr 19 '13 07:04

Kyosuke Nakajima


2 Answers

I recently implemented a custom exception in my Symfony2 service in the following manner:

MemberAlreadyExistsException.php

<?php

namespace Aalaap\MyAppBundle\Services\Membership;

class MemberAlreadyExistsException extends \Exception
{

}

Subscriber.php

<?php

namespace Aalaap\MyAppBundle\Services\Membership;
...
throw new MemberAlreadyExistsException(
    'The member you are trying to subscribe already'
    . ' exists in this list.'
);
...
like image 164
aalaap Avatar answered Sep 27 '22 20:09

aalaap


You can create custom exception the "symfony way" let's look at how exception or created in symfony:

first create your customExceptionInterface

namespace My\SymfonyBundle\Exception;
/**
 * Interface for my bundle exceptions.
 */
interface MySymfonyBundleExceptionInterface
{
}

And create your jsonErrorException

namespace My\SymfonyBundle\Exception;

class HttpException extends \Exception implements MySymfonyBundleExceptionInterface
{
}

Don't hesitate to browse symfony's exceptions code examples on github

like image 37
Paul Valla Avatar answered Sep 27 '22 21:09

Paul Valla