Exceptions misunderstanding...

windows

Guest
I'm throwing exceptions in my database class but when an exception is thrown (due to an SQL error or connection problem) the DB class is always reported as the problem file with the same line numbers in the DB class (the query() or connect() functions).

I would like my exceptions to report the file and line number of the true script at fault - that used the DB class to execute the query.

Do I have to throw the exception from each and every script / class I execute a query from to achieve this?

My existing code:

class Database {

...

private function errHandler($exception)
{

echo sprintf('<div>Error: %s<br />File: %s [%s]</div>',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
);

exit;

}

public function query($sql, $database = NULL)
{

if ($database !== NULL && $database != $this->database)
$this->selectDB($database);

try {
$this->recordset = $this->mysqli->query($sql);

if (!$this->recordset)
throw new Exception($this->mysqli->error);

...

return TRUE;
} catch (Exception $e) {
$this->errHandler($e);
}

}
}foreach (array('username','passwd') as $field)
$$field = sql_escape($_POST[$field]);

$db->query('SELECT ... FROM '.$sqltbl['customer_login'].' WHERE username = '.$username.' AND passwd = PASSWORD('.$passwd.')');

This constantly presents me with the same file and line number when an exception is thrown, not much use for debugging!

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE username = "xxx" AND passwd = PASSWORD("xxx")' at line 1
File: /.../includes/classes/Database.inc [242]What am I doing wrong? Do I need to throw my exceptions outside the DB class?

Any help appreciated.You should throw the exception in your database code, and then try/ catch the exception in the client code, e.g.:

class Database
{
function __construct()
{
throw new Exception( 'test' );
}
}

try
{
$db = new Database;
}
catch( Exception $e )
{
die( $e->getMessage() );
}Thanks for the reply, I'll give this a go.
 
Back
Top