I use whoops on my site, and now I try to get it work with PDO errors, it work fine when there missing a information to connect to the database, but when you (as a example) type a not existing table, it don't show a error.
I have try to add PrettyPageHandler::addDataTable() to my error handel
db.php
class db {
// just some not important code here...
// Try to get the result from database.
try {
$pdo = DB::getInstance()->db->prepare($sql);
$pdo->execute($execute);
$result = $pdo->fetchAll(PDO::FETCH_ASSOC);
// Return Result
return $result;
}
catch(PDOException $e)
{
PrettyPageHandler::addDataTable(null, $e);
}
}
index.php
<?php
if(file_exists("plugins/whoops/autoload.php"))
{
require_once 'plugins/whoops/autoload.php';
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();
}
require_once db.php';
$db = new db();
but then I get a Class 'PrettyPageHandler' not found
You need to use full class name or use statement. Change PrettyPageHandler::addDataTable(null, $e); to \Whoops\Handler\PrettyPageHandler::addDataTable(null, $e);.
Related
This code triggers my editor's intelephense for error:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name']);
} catch (\exception $e) {
throw new \exception($e->getMessage(), $e->getCode());
}
}
Expected 6 arguments. Found 4.intelephense(10005)
would it be fine if I just use:
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'],null,null);
Thank you all for answering; also deceze who corrected me on wrong way to catch exception;
this is edited code:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'], ini_get('mysqli.default_port'), ini_get('mysqli.default_socket'));
} catch (\exception $e) {
echo 'Cannot connect to a database server'; die();
}
}
note ,this is for withing the class using namespaces...
The intelephense plugin uses the stubs from PhpStorm. The author already submitted a PR to fix this (and other functions with optional parameters): https://github.com/JetBrains/phpstorm-stubs/pull/520.
As soon as that's merged and the stubs are updated, you should no longer receive the problem reported in vscode.
There should be no need to change your constructor call, it is valid code and will execute without problems.
I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
I am connecting to MySQL through PDO with Zend\Db from ZF2. How can I report the last errorInfo()?
Here's what I have:
$sqlWriter = new Sql($this->getAdapter());
$insert = $sqlWriter->insert('table_name')->columns(array_keys($data))->values($data);
$stmt = $sqlWriter->prepareStatementForSqlObject($insert);
try {
$stmt->execute();
$object->id = $this->getAdapter()->driver->getLastGeneratedValue();
} catch (\Exception $e) {
//
// HOW CAN I display errorInfo() here?
//
throw new Exception\Exception('Unable to insert record...');
}
I have tried calling methods on the adapter, driver, statement, platform, result, etc... But all to no avail...
EDIT: I found that I can get the info I am looking for by posting the following at the top of the catch block:
$pdoException = $e->getPrevious();
var_dump($pdoException);
I'll leave the question open however since it would be good to know how to execute PDO::errorInfo() directly.
Trying to do exception handling and logging. So if I have something like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
$query->from('#__users');
try
{
$db->setQuery($query);
$result = $db->loadResult();
}
catch (RuntimeException $e)
{
$e->getMessage();
JLog::add('This query failed: '.$query);
}
My question is how best to test my exception code? Taking down the DB will just get Joomla to output this error and I never get into my exception code:
Database connection error (2): Could not connect to MySQL.
I want to be able to verify the exception and log get printed.
This is how I do it. First initialise loggers in entry point file:
JLog::addLogger(
array('text_file' => 'com_mycom.php'),
JLog::ALL ^ JLog::ERROR,
'com_mycom'
);
JLog::addLogger(
array('text_file' => 'com_mycom.errors.php'),
JLog::ERROR,
'com_mycom'
);
Then use it in models:
try
{
$rows = $this->_db->loadObjectList();
}
catch (Exception $e)
{
JLog::add($e->getMessage(), JLog::ERROR, 'com_mycom');
return false;
}
Try adding a throw statement in the try part of your try/catch section.
How do I know if there's an error if I did $db = new SQLite3("somedb.db"); in PHP? Right now the $db doesn't really give me any sort of error?
I can check for file existance, but I'm unsure if there could be any other errors when I open a connection.
You should enable exceptions and instantiate in a try-catch block.
It is not obvious from the documentation but if you use the constructor to open the database it will throw an exception on error.
Further if you set the flag SQLITE3_OPEN_READWRITE in the second argument then it will also throw an exception when the database does not exist (rather than creating it).
class Database extends SQLite3
{
function __construct($dbName)
{
$this->enableExceptions(true);
try
{
parent::__construct($dbName, SQLITE3_OPEN_READWRITE );
}
catch(Exception $ex) { die( $ex->getMessage() ); }
}
Try:
echo $db->lastErrorMsg();