-1

I have no idea to handle error in php, both run-time and compile-time. I want to manage all types of errors.

Notice, Warning, Parse Error, Fatal Error

When these types of errors occur, then I want my program to throw a custom written message on page. Currently I am using try{} catch{}, set_error_handler:

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

In short: I am looking for the right way to handle errors if I type wrong a variable declaration like d instead of $d, or if I forget a semi-colon in a line, or if I get a MySQL error.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
pankaj
  • 1
  • 17
  • 36
  • What research have you done or code have you written? – Script47 Oct 23 '15 at 15:13
  • @Machavity, I disagree with this being a duplicate of that - that question appears to address differences between errors and exceptions. This question asks about handling both types of problems. I'd say it _is_ related though. – HPierce Oct 23 '15 at 15:42

2 Answers2

2

You need to set both, an error handler and an exception handler. When both, errors and uncaught exceptions are thrown you will see both messages displayed:

<?php
function exception_handler($exception) {
    echo "Custom exception message: " . $exception->getMessage() . "\n";
}

function error_handler($errno, $errstr, $errfile, $errline) {
    echo "Custom error message: "  . $errstr . "\n";
}

set_exception_handler('exception_handler');
set_error_handler('error_handler');

//This exception will *not* cause exception_handler() to execute - 
//we have addressed this exception with catch.
try{
    throw new Exception('I will be caught!');
} catch (Exception $e) {
    echo "Caught an exception\n";
}

//Unmanged errors
trigger_error("I'm an error!");
throw new Exception("I'm an uncaught exception!");
?>

outputs:

Caught an exception

Custom error message: I'm an error!

Custom exception message: I'm an uncaught exception!

You can (and should) still use try{} ... catch(){} to address errors as they come up, but these errors will not be handled by the exception handler after the script has finished executing.

More information about exception handlers.

More information about error handlers.

Community
  • 1
  • 1
HPierce
  • 7,249
  • 7
  • 33
  • 49
0

You want to debug your errors not suppress them. Writing code is 25% coding and 75% debugging (arguable). The reason you give to suppress errors is just bad code writing from the start.

megphn
  • 63
  • 7