How to add a custom exception on symfony2

后端 未结 4 373
有刺的猬
有刺的猬 2020-12-09 21:11

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 Sym
相关标签:
4条回答
  • 2020-12-09 21:29

    I just had to add \ and the global scope worked in a Symfony service

    namespace App\CoreBundle\Service;
    
    class CurrencyExchange
    {
        const RATES_XML = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?849b4b329863b2d60bfd0de486e423c9';
    
        const RATES_XML_PATH = 'uploads/ecb_currencies.xml';
    
        /** @var array $rates */
        private $rates;
    
        public function __construct()
        {
            if (!is_file(self::RATES_XML_PATH)) {
                throw new \Exception('XML '.self::RATES_XML_PATH.' does not exists.');
            }
    
            if (1 > filesize(self::RATES_XML_PATH)) {
                throw new \Exception('XML '.self::RATES_XML_PATH.' is empty.');
            }
    
    0 讨论(0)
  • 2020-12-09 21:34

    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

    0 讨论(0)
  • 2020-12-09 21:41

    You have to extend the Exception class, or at least the Symfony's inner exception class

    0 讨论(0)
  • 2020-12-09 21:48

    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.'
    );
    ...
    
    0 讨论(0)
提交回复
热议问题