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
}
}
Related
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.
I am new to php, i am from java background, i am wondering why php doesn't goes directly when exception occured in try block without throwing that exception manually.
e.g.
<?php
//create function with an exception
function checkNum($number) {
if($number/0) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
in above example in if condition the divide by zero exception is occured and then it will directly go to the catch block instead it goes to inside if.why?
The code you posted doesn't do what you say it does.
When you execute:
if ($number/0)
the division by zero prints a warning, and then returns false. Since the value is not truthy, it doesn't go into the if block, so it doesn't execute the throw statement. The function then returns true. Since the exception wasn't thrown, the statement after the call to checkNum(2) is executed, so it prints the message.
When I run your code, I get the output:
Warning: Division by zero in scriptname.php on line 5
If you see this, the number is 1 or below
PHP doesn't use exceptions for its built-in error checks. It simply displays or logs the error, and if it's a fatal error it stops the script.
This has been changed in PHP 7, though. It now reports errors by throwing an exception of type Error. This isn't a subclass of Exception, so it won't be caught if you use catch (Exception $e), you'll need to use catch (Error $e). See Errors in PHP 7. So in PHP 7 you could write:
<?php
//create function with an exception
function checkNum($number) {
if($number/0) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Error $e) {
echo 'Message: ' .$e->getMessage();
}
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.
How do i catch (custom)exceptions (with custom exception handler) that i have thrown in custom shutdown function ? I am not using any framework.
Example:
register_shutdown_function( 'shutdownFunction');
set_exception_handler( 'exceptionHandler');
function exceptionHandler(Exception $exception)
{
// handle and log exception for later debugging...
}
function shutdownFunction()
{
// something is not going right...
if (someVariable != someValue)
throw new RuntimeException('blah...'); // WILL NOT be caught by exception handler
}
// somewhere else in the code...
throw new Exception('something...'); // WILL be caught by exception handler (but not in shutdown function)
The script is using exceptions to communicate that it encountered an error during execution ie. unexpected variable passed to function, database failed to insert row etc...
You simply cannot do this in php.
The register_shutdown_function callback is the last thing that happens in your PHP application. Trying to throw an exception in there will not do anything but invoke a standard php handler. There isn't much to be found on the web regarding these inner workings.
However, I created my own solution for directing it to a single function.
set_exception_handler and register_shutdown_functionare very different functions:
set_exception_handler receives a single argument Exception
register_shutdown_function receives no arguments by default
I've made it so that the set_exception_handler (which receives $exception as argument) sets a property which I can use in the register_shutdown_function.
$lastException = null;
set_exception_handler(function ($e) use (&$lastException) {
$lastException = $e;
});
register_shutdown_function(function() use(&$lastException) {
if($error = error_get_last()) {
$lastException = new \ErrorException($error['message'], $error['type'], 1, $error['file'], $error['line']);
}
if($lastException) {
if (APPLICATION_ENV === 'production') {
Sentry\captureException($lastException);
} else {
var_dump($lastException);
}
}
});
I have no clue if this is a good way to solve the issue, but it allowed me to catch require unexisting_phpfile1389.php errors (Fatal) and regular throw \Exception()s in the same function.
Trying to throw an exception inside the shutdown handler will result in the following exception (how ironic):
( ! ) Fatal error: Uncaught Error: Can only throw objects in
C:...\index.php on line 34
( ! ) Error: Can only throw objects in
C:...\index.php on line 34
You can just wrap the body of your shutdownFunction with
function shutdownFunction()
try {
...
} catch (\Exception $e) {
// do something
}
}
and you will catch all exceptions becase Exception is the base class for all of them
It's quite simple:
function exception_handler (Exception $e) {
if ($e instanceof DBException)
error_handler (['query' => $e->getQuery ()]); // Your actions with your custom Exception object
}
function error_handler ($error) {
if (isset ($error['query']))
echo $error['query'];
else
// Another errors
}
set_error_handler ('error_handler', E_ALL);
set_exception_handler ('exception_handler');
for the first time i came across try, throw catch statement in PHP, and i felt this could be the better way for handling errors as i was quite messing my error handlers with lots of if else statements, however as i am performing CRUD operations on my script i wanted my error handlers to perform two task.
display the user readable or
custom error message back to the
user.
catch all the error in a file for
me to read.
i am using the following code..
try
{
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if($cname == $name)
{
throw new Exception('Sorry, Please Change the value to update ');
}
$sth = $dbh->prepare("UPDATE countries SET name = :name WHERE id = :cid");
$sth->bindParam(':name', $name);
$sth->bindParam(':cid', $cid);
$sth->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents("resources/logs/Connection-log.txt", DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
if the condition $cname == $name is true i just want to display the error 'Sorry, Please Change the value to update, however this is not happening here, instead it throws the Fatal Error with this message.
Fatal error: Uncaught exception 'Exception' with message 'Sorry, Please Change the value to update ' in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php:24 Stack trace: #0 /Applications/MAMP/htdocs/kokaris/administrator/location-manager.php(43): include() #1 {main} thrown in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php on line 24
how do i achieve this?
thank you..
Your catch is catching a PDOException :
catch(PDOException $e)
While you are throwing a Exception :
throw new Exception('Sorry, P...
PDOException is a sub-class of Exception, which means that :
A PDOException is an Exception
But an Exception is not a PDOException.
So, when you are trying to catch a PDOException, your catch will not also catch Exception.
If you want your Exception to be catched, you must use something like this :
try {
}
catch (PDOException $e) {
// deal with PDOException
}
catch (Exception $e) {
// deal with all other kinds of exceptions
}
In this case, the catch PDOException can be avoided, if you do not want to do some special treatment for PDOExceptions, and just want all exceptions to be dealt with the same way :
try {
}
catch (Exception $e) {
// deal with all kinds of exceptions
}
You are throwing an Exception but catching a PDOException.
You should catch the same as you throw, so you might want to change your catch to:
catch(Exception $e)
Or if you also want to catch that PDOException and not do the file_put_contents for your own excpetion, add a catch for your specific Exception.
YOu could ofcourse also change your throw to PDOException, same thing basically.