簡體   English   中英

Symfony覆蓋消息異常

[英]Symfony override message exception

我正在使用 Symfony 5.4 作為 REST API。

我想覆蓋這個 class:(Symfony\Component\Security\Core\Exception\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.';
    }
}

根據我的習慣 class:

<?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';
    }
}

我認為最好的方法是使用裝飾器,但我無法實現。

謝謝您的幫助

我遇到了同樣的問題,由於這個解決方案,我解決了它:

在服務.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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM