Symfony覆盖消息异常

46qrfjad  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(107)

我使用Symfony 5.4作为REST API。
我希望覆盖此类:(Symfony\组件\安全\核心\异常\BadCredentialsException)

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Exception;

/**
 * BadCredentialsException is thrown when the user credentials are invalid.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Alexander <iam.asm89@gmail.com>
 */
class BadCredentialsException extends AuthenticationException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'Invalid credentials.';
    }
}

按我的自定义类:

<?php
declare(strict_types=1);

namespace App\Exception;

use Symfony\Component\Security\Core\Exception\AuthenticationException;

class BadCredentialsException extends AuthenticationException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'Invalid custom message';
    }
}

我认为最好的方法是使用一个装饰,但我不能做到这一点。
谢谢你的帮忙

vjhs03f7

vjhs03f71#

我得到了同样的问题,我解决了它感谢这个解决方案:
服务中.yml:

App\EventListener\AuthenticationFailureListener:    
     tags: - { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_failure, method: onAuthenticationFailureResponse }

而听者:

<?php

class authenticationfailurelistener
{
    public function onauthenticationfailureresponse(authenticationfailureevent $event): void
    {
        $exception = $event->getexception();
        if ($exception instanceof badcredentialsexception) {
            // your logic
        }
        
        $response = new jsonresponse($message, jsonresponse::http_unauthorized);
        $event->setresponse($response);
    }
}

相关问题