1

I use try/catch block in my classes methods, If a get an exception, I log the error. But I would like to tell the "User" that a database query/etc failed - and the problem should be fixed soon. I could use a die() on the Exception in my methods, but that wouldn't be DRY, as I would have to retype it a lot, so any suggestions on how I can do this.

Example method:

public function login($username, $password) {
    try {
        $this->STH = $this->DBH->prepare("SELECT id, baned, activated FROM users WHERE username = ? AND password = ?");
        $this->STH->setFetchMode(PDO::FETCH_OBJ); 
        $this->STH->execute(array($username, $password));

        if (($row = $this->STH->fetch()) !== false)
            return $row;
    } catch (PDOException $e) {
        //Log $e->getMessage();
        die('A database error occoured, we are working on the problem, and it should work in a few...');
    }
}   

2 Answers 2

4

If you need a quick fix, you can set a global exception handler, like this:

function pdo_exception_handler($exception) {
    if ($exception instanceof PDOException) {
        // do something specific for PDO exceptions
    } else {
        // since the normal exception handler won't be called anymore, you 
        // should handle normal exceptions yourself too
    }
}
set_exception_handler('pdo_exception_handler');
Sign up to request clarification or add additional context in comments.

3 Comments

I can't get it to work, with the method above, no result is output, I did an error intentionally..
That handler will be called for uncatched exceptions only, so if you already catch your exceptions somewhere in your code, you should throw them again so the global handler can catch it.
At the end of your catch blocks call throw $e;, where $e is the variable you declared in the catch block. That would still mean to add that line to most of your handlers tho.
1

It's OK to repeat yourself in this case because as each instance of die() passes a unique message.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.