How can I gracefully escape an error condition?

My plugin is freezing the execution of the page at the point where it calls the functions below.

I have two problems…

Read More

1) How can I recode the function so that if there is an error, the plugin does not stop the page from loading, but rather, returns an error message?

2) How can I feedback what the error might be? Its just freezing but not outputting the error.

function rseo_get_seo($check, $post){
 //return false;
    switch ($check)
    {
    case "h1": return rseo_doTheParse('h1', $post);
    case "h2": return rseo_doTheParse('h2', $post);
    case "h3": return rseo_doTheParse('h3', $post);
    case "img-alt": return rseo_doTheParse('img-alt', $post);
    }
}

function rseo_doTheParse($heading, $post)
{
    $content = $post->post_content;
    if($content=="") return false;
    $keyword = trim(strtolower(rseo_getKeyword($post)));
    @$dom = new DOMDocument;
    @$dom->loadHTML(strtolower($post->post_content));
    $xPath = new DOMXPath(@$dom);
    switch ($heading)
        {
        case "img-alt": return $xPath->evaluate('boolean(//img[contains(@alt, "'.$keyword.'")])');
        default: return $xPath->evaluate('boolean(/html/body//'.$heading.'[contains(.,"'.$keyword.'")])');
        }
}

Here’s my attempt to change the 2nd function with try catch but I get a fatal error on plugin activation…

function rseo_doTheParse($heading, $post){
try { //I get a FATAL error here. unexpected '{'
    $content = $post->post_content;
    if($content=="") return false;
    $keyword = trim(strtolower(rseo_getKeyword($post)));
    @$dom = new DOMDocument;
    @$dom->loadHTML(strtolower($post->post_content));
    $xPath = new DOMXPath(@$dom);
    switch ($heading)
        {
        case "img-alt": return $xPath->evaluate('boolean(//img[contains(@alt, "'.$keyword.'")])');
        default: return $xPath->evaluate('boolean(/html/body//'.$heading.'[contains(.,"'.$keyword.'")])');
        }
    }
    catch (Exception $e)
    {
        echo 'Exception caught: ',  $e->getMessage(), "n";
    }
}

Related posts

Leave a Reply

2 comments

  1. For debugging you could also use the following syntax instead of try/catch:

    if (!$x) {
       throw new Exception('Division by zero.');
    }
    else return 1/$x;
    

    or use good old var_dump($x); which often tells you enough to get you going again.