trigger_error(): Generates a user-level error/warning/notice message

This creates user level error messages.
<?Php
$price_sell=100;
$price_buy=120;
if($price_sell<=$price_buy){
 trigger_error("Do you want to sell without profit?");
}
?>
Output
Notice: Do you want to sell without profit? in C:\xampp\htdocs\t\checking.php on line 5
We can manage the error level also.
trigger_error("Do you want to sell without profit?",E_USER_ERROR);
Output
Fatal error: Do you want to sell without profit? in C:\xampp\htdocs\t\checking.php on line 5
User-generated notice message.
trigger_error("Do you want to sell without profit?",1024);
Output
Notice: Do you want to sell without profit? in C:\xampp\htdocs\t\checking.php on line 5
Syntax
trigger_error(string $message, int $error_level = E_USER_NOTICE)

user_error(): This function is an alias of: trigger_error()

Example 2: Triggering Different Error Levels

You can specify the type of error you want to generate using different constants:

trigger_error("This is a warning.", E_USER_WARNING); // User warning
trigger_error("This is an error.", E_USER_ERROR); // User error
trigger_error("This is a notice.", E_USER_NOTICE); // User notice

Example 3: Using trigger_error() in a try-catch Block

You can handle custom errors inside a try-catch block for better control:

set_error_handler(function($errno, $errstr) {
    throw new ErrorException($errstr, $errno);
});
try {
    trigger_error("Custom error.", E_USER_ERROR);
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}

Use Case: Validation Error with trigger_error()

Use *trigger_error()* in form validation to display custom error messages for invalid inputs:

$age = -5;
if ($age < 0) {
    trigger_error("Age cannot be negative.", E_USER_WARNING);
}

Example 4: Combining trigger_error() with error_log()

You can log errors to a file for later analysis:

ini_set("log_errors", 1);
ini_set("error_log", "/path/to/error.log");
trigger_error("Logging this error.", E_USER_NOTICE);

Introduction to PHP Managing Error
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer