Cómo manejar condiciones de error de forma elegante en WordPress

14 ene 2011, 22:25:25
Vistas: 325
Votos: 1

Mi plugin está congelando la ejecución de la página en el punto donde llama a las funciones siguientes.

Tengo dos problemas...

1) ¿Cómo puedo recodificar la función para que si hay un error, el plugin no detenga la carga de la página, sino que devuelva un mensaje de error?

2) ¿Cómo puedo obtener información sobre cuál podría ser el error? Simplemente se congela pero no muestra el error.

function rseo_get_seo($check, $post){
 //retorna 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.'")])');
        }
}

Aquí está mi intento de cambiar la segunda función con try catch pero obtengo un error fatal al activar el plugin...

function rseo_doTheParse($heading, $post){
try { //Obtengo un error FATAL aquí. '{' inesperado
    $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 'Excepción capturada: ',  $e->getMessage(), "\n";
    }
}
2
Comentarios

intenta eliminar el carácter @ antes de $dom

onetrickpony onetrickpony
14 ene 2011 23:20:57

Try/catch solo funciona en php 5+. ¿Qué versión estás ejecutando?

MathSmath MathSmath
15 ene 2011 00:54:39
Todas las respuestas a la pregunta 2
0

Para depuración también puedes usar la siguiente sintaxis en lugar de try/catch:

if (!$x) {
   throw new Exception('División por cero.');
}
else return 1/$x;

o usa el viejo confiable var_dump($x); que frecuentemente te dice lo suficiente para continuar.

28 ene 2011 15:15:50
0

Esta línea está incorrecta:

$xPath = new DOMXPath(@$dom);

Debería ser esta:

$xPath = new DOMXPath($dom);
28 feb 2011 03:01:34