PHP.mk документација

trigger_error

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.trigger-error.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.trigger-error.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
trigger_error

Референца за `function.trigger-error.php` со подобрена типографија и навигација.

function.trigger-error.php

trigger_error

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

trigger_errorГенерира порака за грешка/предупредување/известување на ниво на корисник

= NULL

trigger_error(string $message, int $error_level = E_USER_NOTICE): true

Се користи за активирање на корисничка состојба на грешка, може да се користи во комбинација со вградениот ракувач со грешки, или со кориснички дефинирана функција која е поставена како нов ракувач со грешки (set_error_handler()).

Оваа функција е корисна кога треба да генерирате специфичен одговор на исклучок во време на извршување.

Параметри

message

Назначената порака за грешка за оваа грешка. Ограничена е на 1024 бајти. Сите дополнителни знаци над 1024 бајти ќе бидат скратени.

error_level

Назначениот тип на грешка за оваа грешка. Работи само со E_USER_* константите од семејството, и ќе се врати на E_USER_NOTICE.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Поминување E_USER_ERROR како error_level е сега застарена. Фрли Исклучок или повикај exit() instead.

Вратени вредности

Секогаш враќа true.

Errors/Exceptions

Оваа функција фрла ValueError if error_level не е една од E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_USER_DEPRECATED.

Дневник на промени

Верзија = NULL
8.4.0 Поминување E_USER_ERROR како error_level е сега застарена. Фрли Исклучок или повикај exit() instead.
8.4.0 Функцијата сега има тип на враќање true наместо bool.
8.0.0 Функцијата сега фрла ValueError ако е невалиден error_level е специфициран. Претходно, враќаше false.

Примери

Пример #1 trigger_error() example

Константи за известување за грешки set_error_handler() за поопширен пример.

<?php
$password
= $_POST['password'] ?? '';
if (
$password === '') {
trigger_error("Using an empty password is unsafe", E_USER_WARNING);
}
$hash = password_hash($password, PASSWORD_DEFAULT);
?>

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

HTML ентитети во message не се избегнати. Користи htmlentities() на пораката ако грешката треба да се прикаже во прелистувач.

Види Исто така

Белешки од корисници 6 белешки

некој на attbi dot com
пред 22 години
the idea is never to give out file names, line numbers, and cryptic codes to the user. Use trigger_error() after you used set_error_handler() to register your own callback function which either logs or emails the error codes to you, and echo a simple friendly message to the user.

And turn on a more verbose error handler function when you need to debug your scripts. In my init.php scripts I always have:

if (_DEBUG_) {
    set_error_handler ('debug_error_handler');
}
else {
    set_error_handler ('nice_error_handler');
}
Хауард Јинд
пред 16 години
trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful.

eg:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
if(is_numeric($var)) {
 /* do some stuff*/
} else {
 trigger_error('var must be numeric');
}
}
?>

will output "Notice: var must be numeric in functions.php on line 6"
whereas "Notice: var must be numeric in main.php on line 4" would be more useful

here's a function to do that:

<?php

function error($message, $level=E_USER_NOTICE) {
$caller = next(debug_backtrace());
trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

So now in our example:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
    if(is_numeric($var)) {
         /* do some stuff*/
    } else {
         error('var must be numeric');
    }
}

function error($message, $level=E_USER_NOTICE) {
    $caller = next(debug_backtrace());
    trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

now outputs:

"Notice: var must be numeric in doFunction called from main.php on line 4"
ричард на 2006 dot atterer dot net
19 години пред
Beware, trigger_error() is absolutely useless for transporting your own function's error messages in $php_errormsg:

ini_set('track_errors', TRUE);
function x() { trigger_error('MY ERROR'); }
@x();
echo "Error 1: \\"$php_errormsg\\"\\n";
@file_get_contents('/nonexisting');
echo "Error 2: \\"$php_errormsg\\"\\n";

This outputs:

Error 1: ""
Error 2: "failed to open stream: No such file or directory"

This behaviour is consistent with the description of $php_errormsg, which says that the variable will only be available within the scope in which the error occurred. The problem can be worked around with a custom error handler like the one below. However, I'm undecided whether changing the language in this way is good:

function errHandler($errno, $errstr, $errfile, $errline) {
  global $php_errormsg; $php_errormsg = $errstr;
}
set_error_handler('errHandler');
aydin dot kn12 at gmail dot com
пред 11 години
If error_type is E_USER_ERROR then trigger_error throw FATAL ERROR and script stopped after this line.

<?php

$msg = 'This is the test message for echo';

trigger_error('Error message', E_USER_ERROR); // Script stopped after this line...

echo $msg; // This line does not appear...

?>
PhpMyCoder
пред 15 години
For those of you looking to use your own file or line number in the error (possibly using debug_backtrace()) instead of the ones created by trigger_error(), here is a solution:
Create a custom function to handle E_USER_ERRORs that simply outputs the error type and message, while excluding the line number and file trigger_error() reports. You may also configure it to handle user warnings and notices if necessary (I did in the example below).

<?php
function error_handler($level, $message, $file, $line, $context) {
    //Handle user errors, warnings, and notices ourself
    if($level === E_USER_ERROR || $level === E_USER_WARNING || $level === E_USER_NOTICE) {
        echo '<strong>Error:</strong> '.$message;
        return(true); //And prevent the PHP error handler from continuing
    }
    return(false); //Otherwise, use PHP's error handler
}

function trigger_my_error($message, $level) {
    //Get the caller of the calling function and details about it
    $callee = next(debug_backtrace());
    //Trigger appropriate error
    trigger_error($message.' in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong>', $level);
}

//Use our custom handler
set_error_handler('error_handler');

//-------------------------------
//Demo usage:
//-------------------------------
function abc($str) {
    if(!is_string($str)) {
        trigger_my_error('abc() expects parameter 1 to be a string', E_USER_ERROR);
    }
}

abc('Hello world!'); //Works
abc(18); //Error: abc() expects parameter 1 to be a string in [FILE].php on line 31
?>

This is a pretty simple concept and I'm sure most of you know this, but for those that don't, let it serve as a good example!
theking2 на king точка ma
пред 1 година
The function trigger_error will terminate the script if $error_level is equal or higher than E_USER_ERROR. 

If you write your own error handler you will have to do these yourself.

Example in which we assume the global LOG constant points to a PSR2 logging interface.
<?php

set_error_handler( function ($errno, $errstr, $errfile, $errline) {
    // error was suppressed with the @-operator
    if( 0 === error_reporting() ) {
        return false;
    }
    switch($errno) {
        default:
            LOG->error( "Unknown error type: [$errno] $errstr", [ 'file' => $errfile, '@' => $errline ] );
            exit(1);

        case E_USER_ERROR: // fall through
        case E_WARNING: // treat PHP warnings are errors
            LOG->error( $errstr, [ 'file' => $errfile, '@' => $errline ] );
            exit(1);

        case E_USER_DEPRECATED:
        case E_DEPRECATED:
            LOG->error( "DEPRECATED $errstr", [ 'file' => $errfile, '@' => $errline ] );
            break;

        case E_USER_WARNING: // fall through
        case E_NOTICE: // treat PHP notices are warnings
            LOG->warning( $errstr, [ 'file' => $errfile, '@' => $errline ] );
            break;

        case E_USER_NOTICE:
            LOG->notice( $errstr, [ 'file' => $errfile, '@' => $errline ] );
            break;

        case E_ERROR: // fall through
        case E_RECOVERABLE_ERROR:
            LOG->critical( $errstr, [ 'file' => $errfile, '@' => $errline ] );
            exit(1);

    }
    /* Don't execute PHP internal error handler */
    return true;
} );
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.