albertedevigo
albertedevigo

Reputation: 18411

How to handle PHP exceptions and keep it semantic?

I'm developing for a project where HTML designers use PHP methods to retrieve content. Now, it's the time for handling exceptions and we are running into problems to simultaneously keep the HTML pretty, clean and semantic and the PHP correct.

Until exceptions, HTML templates had things like:

<h2 class="title"><?php Content::getTitle() ?></h2>

Now, if we want to handle exceptions, we are supposed to write:

<h2 class="title">
    <?php
    try {
        Content::getTitle();
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    ?>
</h2>

Which is anything but clean.

Or

<?php
try {
    // THE WHOLE TEMPLATE RENDERING!!!
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Which is unacceptable because it stops rendering at any exception, when it should report the problem and continue.

So, we are thinking about putting the try/catch stuff inside the method itself:

class Content {

    public static function getTitle {
    try {
        if (something==happened) throw new Exception 'OMG!';
        else {
            DoTheJob();
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }

}

It seems to work by the moment so the question is: is this a good practice? Is there a better and more DRY alternative?

Upvotes: 2

Views: 376

Answers (2)

Gordon
Gordon

Reputation: 316959

Yes, this is fine and sound. It is called the Template View Pattern:

The best way to work with dynamic webpages [sic] is to compose the dynamic Web page as you do a static page but put in markers that can be resolved into calls to gather dynamic information. Since the static part of the page acts as a template for the particular response, I call this a Template View.

More details can be found in Fowler, Patterns of Enterprise Application Architecture.

Upvotes: 1

Mikulas Dite
Mikulas Dite

Reputation: 7941

What you are discussing are earlier phases of MVC. You definitely want to split the code login (exception handling) from your templates. It's totally recommendable to have the exception logic in appropriate method (or above, of course).

What you actually don't want to do is simply print the error, that would generally confuse users. If you have already outputted partial content, you have a decision whether to redirect to an error page or render a generic user friendly error message in the broken page (given you don't know how much you have rendered already).

It might also be viable to catch exceptions not accounted for (ie those you have to halt on) with set_exception_handler. That's totally dry.

Upvotes: 1

Related Questions