Hi all, Translation of Exceptions

2 months ago

dianecrowe04us
Member | 1
+
0
-

Hi all im a new. Nice to meet you.

And second,

Has anyone a solution for translate the thrown exeptions from Nette without changing the main classes.

For examle the SimpleAuthenticator Class is throwing a

AuthenticationException(‘Invalid password.’, self::INVALID_CREDENTIAL);

or

AuthenticationException(“User ‘$username’ not found.”, self::IDENTITY_NOT_FOUND);

I use Kdyby/Translation, but i find no solution für translate this Exception text to german with this extension.

2 months ago

jiri.pudil
Member | 928
+
+9
-

Hello and welcome!

I don't think it's a good idea to translate exception messages directly – they are meant for the developer, not for the user. You can use the exception code to distinguish different authentication failures and get the right translation key, e.g. like this:

try {
    $authenticator->authenticate(...$credentials);
} catch (AuthenticationException $e) {
    switch ($e->getCode()) {
        case IAuthenticator::IDENTITY_NOT_FOUND:
            $message = 'authentication.error.userNotFound'; break;
        case IAuthenticator::INVALID_CREDENTIAL:
            $message = 'authentication.error.invalidPassword'; break;
        default:
            $message = 'authentication.error.unknownError';
    }

    $this->flashMessage($message, 'error');
}