My stackoverflow answer #1

by krike in Other / Q&A on 24 Aug 2010

Stackoverflow is one of the websites I visit the most because it’s a place where I can get help really fast but it’s also a place where I can help other people. Therefore I will feature one of my answers each week and who knows it might help you out as well. The question This [...]

Stackoverflow is one of the websites I visit the most because it’s a place where I can get help really fast but it’s also a place where I can help other people. Therefore I will feature one of my answers each week and who knows it might help you out as well.

The question

This weeks question by RPK:

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.

My anwser

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

Author:

Christophe (aka krike) is a Web designer & developer living in Belgium. He spends most of his time working with Wordpress, CodeIgniter & Photoshop but also helping beginners take their first step in the development world.

Drop us a word

Spam Protection by WP-SpamFree