0

Part 1:
Let's say I do something which throws an exception like:

function do_something($somepar)
{
    if (inexistent())
        return TRUE;
    else
        return FALSE;
}
if (do_something("SMART"))
    echo "Everything went right";
else
    echo "Something failed";

I got

Fatal error: Call to undefined function inexistent() in xyz.php on line 123

Is it possible to localize this message? I hoped

setlocale(LC_ALL,'it_IT');

could do that but it didn't.

Part 2:
which is your recommendation to handle localized errors. Let's say I want to create a general function to public it on the web and can be used by people who want it to use their own language.

function do_something($somepar)
{
    if (whatever())
    {
        return TRUE;
    }
    else
    {
        $error_message = localizeThis("How to translate this?");
        trigger_error($error_message, E_USER_ERROR);
        return FALSE;
    }
}
if (do_something("SMART"))
    echo "Everything went right";
else
    echo "Something failed";

Also how to set the correct output language?

Luca Borrione
  • 16,324
  • 8
  • 52
  • 66
  • Trying to catch a fatal error? http://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error – wesside Sep 14 '12 at 13:36
  • BTW, errors are not exceptions. Those are separate error handling concepts in PHP. – deceze Sep 14 '12 at 15:31

1 Answers1

3

You need to differentiate between error handling, debugging/error messages and user-visible output. The standard error messages triggered by PHP are not localized by PHP. They are exclusively for the developer to see to help the developer debug the application, and the developer is expected to speak English. The rest of the PHP language is in English anyway.

Messages triggered by trigger_error or by thrown exceptions are not meant for end-user consumption, as most end users won't understand them anyway. You need to catch those errors internally and, if necessary, notify the user with any sort of localization system that something bad happened. The technical error messages can also contain sensitive information that should not be disclosed to the general public. So:

set_error_handler(function ($errno, $errstr) {
    logErrorToFile($errstr);

    switch ($errno) {
        case E_ERROR :
            die(_('Sorry, something bad happened. Please read this comforting localized error instead'));
        case E_NOTICE :
            // decide what you want to do here
        ...
    }
});

and:

try {
    somethingThatThrowsExceptions();
} catch (Exception $e) {
    logErrorToFile($e->getMessage());
    die(_('Sorry, something bad happened. Please read this comforting localized error instead'));
}
deceze
  • 510,633
  • 85
  • 743
  • 889