Best option to be used in error handling?

Asked

Viewed 1,373 times

2

I’m creating a library in PHP to make the connection to the database and manipulate data from it, but do not know what is the best option to handle the errors, if it is better to use try/catch, echo/return or die.

I am currently using several if/else to go through (validate) the data, in case of error I display a echo with the mistake and I give a return false (not to execute the remaining code), if there is no error, just continue my checks and at the end return true or array (depending on function). See an example of my simplest function (the deletar):

function deletar($tabela, $where = NULL)
{
    if(!function_exists("conectar"))
    {   //falta include de conexao.php
        echo "Não há uma conexão ativa com o seu banco de dados!\n<br><i>Inclua a página ../conexao.php<br>";
        return false;
    }
    else
    {
        //conexao feita
        if($tabela)
            $tabela = "DELETE FROM ".$tabela." ";
        else
        {
            echo "<br>Não foi indicada nenhum tabela.<br>";
            return false;
        }

        $where = minwhere($where);

        echo $sql = $tabela.$where;

        if($conn = conectar())
        {
            if($result = $conn->query($sql))
            {
                $stmt = $conn->prepare( $sql );
                if($result = $stmt->execute())
                        echo "<br>Deletado!<br>";
                else
                    echo "<br>Query inválida!<br>";

                $conn = null;
                return true;
            }
            else
            {
                echo "<br>Query inválida!<br>";
                return false;
            }  
        }
        else
        {
            echo "<br>Não foi possível conectar-se ao banco de dados!<br>\n<i>Verifique as variáveis do arquivo ../conexao.php</i>";
            return false;
        }
    }
};

Follows the rest of the library (if someone wants to analyze other functions).

What can improve error handling? The mode I’m doing is a valid alternative or bad code?

  • 2

    Enjoy and see this and here has an example of a Soen user-made Builder query that answers a lot about php.

2 answers

4


Basically right, it could only be more organized. I could organize even more than I did below, but I would run away from the style being done.

That pile of echo It’s always a shallow way to deal with the mistake. In serious applications, the treatment would be done in a totally different way, never play a text anyway on the page. But for that you would have to restructure the entire application, not just this section. I even understand that most people do so, but it is the "pig" way of doing.

Honestly, because it’s a library, I thought it was a horrible code. It sounds like code from someone who’s starting programming. I wouldn’t follow her to learn.

function deletar($tabela, $where = NULL) {
    if(!function_exists("conectar")) {
        echo "Não há uma conexão ativa com o seu banco de dados!\n<br><i>Inclua a página ../conexao.php<br>";
        return false;
    }
    if(!$tabela) {
        echo "<br>Não foi indicada nenhum tabela.<br>";
        return false;
    }
    $tabela = "DELETE FROM ".$tabela." ";
    $where = minwhere($where);
    echo $sql = $tabela . $where;
    if(!($conn = conectar())) {
        echo "<br>Não foi possível conectar-se ao banco de dados!<br>\n<i>Verifique as variáveis do arquivo ../conexao.php</i>";
        return false;
    }
    if($result = $conn->query($sql)) {
        $stmt = $conn->prepare( $sql );
        echo ($result = $stmt->execute()) ? "<br>Deletado!<br>" : "<br>Query inválida!<br>";
        $conn = null; //isto provavelmente é um erro
        return true;
    }
    echo "<br>Query inválida!<br>";
    return false;
}

I put in the Github for future reference.

I deal with the subject in another question.

  • Thanks for the tip, I don’t think it’s the right way to do it either, but I do it because I can’t do it any other way. It would be nice to have a library of errors and error codes, but I don’t know how to do so I asked. The echo are the only way I found to directly report the error. I noticed that commented a line, the variable $conn is my connection to the database, matching it to null would be the closure of the connection (according to a question I saw here in Stack)

  • 4

    Yeah, here’s a lot of wrong stuff being disseminated, mostly in PHP. A library that manages the connection should never give echo, should inform who will consume the connection to present in a way that fits that site. That’s why I said I needed to restructure the whole code. You have to separate logic from connection, from presentation logic. You can even make one log there, but you can’t write anything on the page, you don’t know how it will be presented, you don’t even know if it’s a page or something.

  • In case, do the treatment creating Exception would be more appropriate than the if/else and echo ?

  • 1

    I don’t think so, some people think so, but especially in PHP, I am against the use of exceptions. I talk about this in link that I put in the reply. Almost no one knows how to use exceptions right, and that alone is a good reason not to use. It has better reasons.

  • 1

    There are several ways to deal with errors, you can even use trigger_error and direct with the set_error_handler, or with the try catch, but using these methods you are subject to other complications, depending on what you want in the end, it is most often recommended to store errors in a specific variable so that we have more control over when and where we should present this error. But even this way of dealing with errors has cons. The linked question has more detailed information about some methods.

2

Solution using try catch

try {

    if(!function_exists("conectar")) {
        throw new Exception( "Não há uma conexão ativa com o seu banco de dados!\n<br><i>Inclua a página ../conexao.php<br>" );
    }
    if(!$tabela) {
        throw new Exception( "<br>Não foi indicada nenhum tabela.<br>" );
    }

    $tabela = "DELETE FROM ".$tabela." ";
    $where = minwhere($where);
    echo $sql = $tabela . $where

    if(!($conn = conectar())) {
        throw new Exception( "<br>Não foi possível conectar-se ao banco de dados!<br>\n<i>Verifique as variáveis do arquivo ../conexao.php</i>" );
    }

    $result = @$conn->query($sql);

    if(!$result) {
        throw new Exception( "<br>Query inválida!<br>" );
    }

    $stmt = $conn->prepare( $sql );
    echo ($result = $stmt->execute()) ? "<br>Deletado!<br>" : "<br>Query inválida!<br>";
    $conn = null; //isto provavelmente é um erro
    return true;

} catch( Exception $e ) {

    echo $e->getMessage();
    return false;
}
  • 1

    I did it, but I created a class Exception empty, just under another name, in operation changes something? Or just the same name?

  • It depends on whether this new class extends from Exception so the operation remains the same.

  • I think it’s not a very good idea to make exceptions left and right...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.