Unable to catch an SQL exception - php

I have a Database class:
<?php
namespace Database\MySQL;
class Database
{
function __construct(){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$this->Connection = new mysqli(
"", // Testing with no host
"", // Testing with no user
"", // ... no password
"" // and no DB name
);
}
catch (mysqli_sql_exception $e) {
throw $e;
}
...
?>
But instead of a getting an exception, I get a Fatal error: Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'No database selected' in Database.php.
I have tried the same thing with a simple query:
try {
$this->Connection->query("SET NAMES 'utf87'"); //utf87 just for test
}
catch (mysqli_sql_exception $e) {
throw $e;
}
And I still get Fatal error: Uncaught exception.

Your problem is that you are catching the exception, but then just throwing it again without catching it.
If you replace throw $e; with echo "Caught the exception";, you will see that your script is catching the exception. But because you throw it again, it will result in an error unless you have a higher-level try/catch block or a global exception handler.
Also, as many have pointed out in the comments, you need to be careful of namespaces. You need to use a use statement or refer to \mysqli_sql_exception.

Related

How to catch specific Exception

I sometimes get in the log PHP Fatal error: Uncaught Exception: Connection reset by peer on socket_read()
How can I catch and ignore only this one exception, re-throwing any other?
My example handles all exceptions. If the exception contains the phrase, it allows you to handle that, otherwise, it rethrows an error message.
try {
// Your Code
} catch (Exception $e) {
if ( ! strpos($e->getMessage(), "Connection reset by peer") === false )
throw $e; // THROW IT, ITS A DIFFERENT ERROR
else
{
// Do Your Handling Code
}
}

Laravel exception not catching

I'm trying to do a very basic exception try catch, but it doesn't catch.
$id =0;
try {
$question = $this->model->find($id); // will not find anything since $id = 0
$question->delete(); // throw an exception
return true;
} catch (\Exception $e) {
dd ('hello'); // should end up here, but no?!?!?
} catch (FatalThrowableError $f) {
echo ("fatal"); // or here... but no.
}
but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.
I have tried
use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;
or simply
Exception;
FatalThrowableError;
Also, having the \Exception $e or Exception $e (with or without ) doesn't change anything.
Note that if I add a line like $foo = 4/0 I get into the Exception section (dd (hello)).
in .env APP_DEBUG=true, APP_LOG_LEVEL=debug
I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.
http://php.net/manual/en/language.errors.php7.php
As the Error hierarchy does not inherit from Exception, code that uses
catch (Exception $e) { ... } blocks to handle uncaught exceptions in
PHP 5 will find that these Errors are not caught by these blocks.
Either a catch (Error $e) { ... } block or a set_exception_handler()
handler is required.
You can, additionally, catch (\Throwable $e) {} to account for both Error and Exception types.

try{...}catch does not throw exception in PHP/Symfony2/PHPImap

I am using the ImapMail Library and try to initiate a new Mailbox:
try{
$mailbox = new ImapMailbox($url, $username, $password);
}catch (\Exception $e){
return new Response("fail");
}
But the above try/catch does not work, although symfony gives me this:
Connection error: (is empty)
500 Internal Server Error - Exception
the Stacktrace
in vendor/php-imap/php-imap/src/PhpImap/Mailbox.php at line 67:
protected function initImapStream() {
$imapStream = #imap_open($this->imapPath, $this->imapLogin, $this->imapPassword, $this->imapOptions, $this->imapRetriesNum, $this->imapParams);
if(!$imapStream) {
throw new Exception('Connection error: ' . imap_last_error());
}
return $imapStream;
}
(Direct link to function on github)
It does throw a new Exception, why can't I catch it?
Any hint appreciated!
The reason is very simple. You call only class constructor in try block. If you look into the class source code, you will see that constructor does call nothing.
https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L20-L31
It means code throwing exception must be under you try/catch. You have to move it inside try block if you want to catch the exception. I am talking about $mailbox->checkMailbox(). This command throws exception.

php pdo catching connection exception with custom exception handler

What im trying to achieve here , is when the pdo connection throws an exception , my custom exception handler takes the message and passes it on so i can catch it with my custom exception handler.
try {
$mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
}
catch (PDOException $e) {
$a = $e->getMessage();
throw new customException ( "Failed to connect to MySQL:". $a );
die();
}
catch (customException $e){
echo $e->errorMessage();
}
BUT it returns this error :
Fatal error: Uncaught exception 'customException' with message ......
Wrap it in another try-catch block.
try {
try {
$mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
} catch(PDOException $e) {
$a = $e->getMessage();
throw new customException ( "Failed to connect to MySQL:". $a );
}
} catch(customException $e) {
echo $e->errorMessage();
// Do what you want
}
You are confusing custom exception handler with custom exception class. You need the former one and the other answer is wrong.
Explanation.
In your application code you have to writing one single line only:
$pdo = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
without multiple tries and stuff. Just the code you need to run.
While all the handling logic goes into handler

Exception not catch by Try/Catch in PHP

i've try this example :
<?php
try {
Not_Exist();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
http://php.net/manual/en/language.exceptions.php
But the error is not catched :
Fatal error: Call to undefined function Not_Exist() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\mysite\public_html\exception.php on line 3
Why? I'm usually using Dotnet. Maybe i miss something.
error is not an exception. PHP itself doesn't throw exceptions on syntax errors, such as missing functions. You'd need set_error_handler() to "catch" such things - and even then, a custom error handler can't handle parse errors such as this.
There is no Exception being thrown in your code. You're simply hitting a fatal error. If you're trying to find a way around fatal errors, this post may be of help. How do I catch a PHP Fatal Error
If you're trying to catch Exceptions, something like this:
try {
throw new Exception("Exception Message");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Because that is a fatal error, not an exception. You're going to want to use PHP's function_exists() method and try something like:
try{
function_exists(Not_Exist);
} catch (Exception $e) {
// error here
}
// run Not_Exist here because we know its a valid function.

Categories