Specific exception error message

If I setup an exception for connecting to my database, how can I get a more specific error message?

For example I want to know what part of the connection failed; was no database found, was the password wrong etc etc.

At the moment I only get my generic custom message about not being able to connect. I realise you can get the line number of the error by using the method e->getLine() but was wondering if there was something more descriptive I could append to my catch output?


	public function connect(){

		try {
			$config = include('config.php');
			$conn = $mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
			if (!$conn) throw new exception('Could not connect to the database.');	
			$output = '<p class="success">Connection successful</p>';
			}
		catch (Exception $e) {
			$output = '<p class="error">'.$e->getMessage().'</p>';
			return $output;
			}	
		
		mysqli_set_charset($mysqli, 'utf8');
		return $output;

	}

Thanks heaps!!!

Create specific exception types for the conditions you want to handle differently, and throw those instead of a generic exception object.

I’ve seen similar to this before…


<?php
class Database_Exception extends Exception
{
    const ACCESS_DENIED_ERROR = 1045;
    
    public function __construct($message, $code){
        parent::__construct($message, $code);
    }
}

class Database
{
    public function __construct(){
        if(false === is_resource($connection)){
            throw new Database_Exception(mysqli_error(), mysqli_errno());
        }
    }
}

try{
    $database = new Database();
}catch(Database_Exception $exception){
    switch($exception->getCode())
    {
        case Database_Exception::ACCESS_DENIED_ERROR:
            echo 'Access Denied.';
        break;
    }
}