I have various functions in a class. In each function I use try...catch. Is there any way to simplify this? I want to make one error class and it must be accessible from any file in my project. I don't want to use try..catch in each function, rather it should be automatically directed to the Error class.
Register a global exception catcher. This function will catch any uncatched exception. You should do it as you do with register_session, that is, in some file which is included in every page, so that it works across the site.
See: http://php.net/manual/en/function.set-exception-handler.php
But note that you cannot recover from such an exception (you can't handle error and continue).
Hi, Basically this is a requirement is almost all projects as they get bigger. The solution is to create a Error handling module. You can create one from scratch or use already existing awesome modules like ELMAH.
I do not add the try catch in the function itself but in the page where the function is called.
eg:
try
{
$faq_title = mysqli_real_escape_string($link, $_POST['faq_title']);
$faq_subtitle = mysqli_real_escape_string($link, $_POST['faq_subtitle']);
$desc = mysqli_real_escape_string($link, $_POST['desc']);
$faq_e = new Shopadmin();
$faq_e->add_faq($faq_title, $faq_subtitle, $desc);
$feedback = "<div class='succes'>FAQ added succesfully!</div>";
}
catch(Exception $e)
{
$feedback = "<div class='error'>";
$feedback .= $e->getMessage();
$feedback .= "</div>";
}
and in my function I check if the query was done succesfully or not, if not I throw a new exception which will be catched and stored into $feedback which I echo out on the main container div.
this way you can call for different functions withouth having to add the try catch in each function
I hope this helps you out