0

I have a database class dbconnect.php, and processform.php. Inside dbconnect.php there is a method for connecting to the database.

If there's an error, how do I throw an exception? Where do I put the try catch block, in the processform.php? People say I shouldn't echo an error directly from inside the class. Here's an example:

    <?php

    // dbconnect.php

    class DbConnect
    {

        public function open_connection()
        {

            /* Should I do it like this? */
            $this->conn = PDO($dsn, $this->username, $this->password);
            if (!$this->conn) {
                throw new Exception('Error connecting to the database.');
            }

            /* Or like this */
            try {
                $this->conn = PDO($dsn, $this->username, $this->password);
            } catch (PDOException $e) {
                echo 'Error: ', $e->getMessage(), '<br>';
            }
       }
    ?>

    // processform.php

    <?php
        require_once 'dbconnect.php';
        $pdo = new DbConnect($host, $username, $password);
        try {
            $pdo->open_connection();
        } catch (PDOException $e) {
            echo 'Error connecting to the database.');
        }
    ?>

I really want to learn the correct way of implementing the try catch in my code.

2 Answers 2

1

You don't have to throw an exception manually, especially on a successful connect :-)

Instead you need to tell PDO that it needs to throw exceptions when something goes wrong and you can do that when you open your database connection:

$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);

Now you can put everything in try / catch blocks but that is not even necessary; if you don't do that, php will show you unhandled exceptions complete with a stack trace when you don't catch them manually.

And when you decide you want to fine-tune your error handling for your visitors, you can set your own exception handler using set_exception_handler(). That way you can handle everything at one place instead of wrapping different sections in try / catch blocks. Should you prefer that of course.

Sign up to request clarification or add additional context in comments.

Comments

0

In my practice, I prefer to catch exception in bottom. I mean, second way in your DbConnect.

You can output error message to error log. And return an error code to front-end. So the front-end knows how to tell users an error occours in a friendly way.

What's more, you can use global error handler such as set_error_handler/set_exception_handler to do this. Redirect to an error page when error occours.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.