I am confused in an issue. I have thrown an exception for unauthorized user in a function. When I call this function it shows *Fatal error: Uncaught exception 'HTTPErrorException' *
My code is
throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
How can I catch this Exception so that I can show some CSS instead of the stack trace which is comming
the error code shows that you haven't caught the exception, so it will throw this error. every exception should be caught by your code
try {
....
throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
....
} catch (HTTPErrorException $e) {
// generate a stack trace here and show it to user
// you can use $e->getTraceAsString() or $e->getTrace() functions here to get stack trace
}
or if you don't want to use try / catch blocks then you can create a exception handler function that will be called whenever your application has not caught the exception anywhere
function exception_handler($exception) {
echo "Custom Exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
check more about exceptions http://php.net/manual/en/language.exceptions.php
Related
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
}
}
I am trying to use a try/catch block to add in some error handling for a custom WordPress plugin that gets Tweets via the Twitter API.
For testing purposes, I am throwing an exception in my class construct method.
class Twitter_Settings() {
public function __construct() {
throw new \Exception('test');
}
}
then in my plugin file, I am doing:
function twitter_init_settings() {
try {
return new Twitter_Settings();
} catch ( Exception $e ) {
echo $e->getMessage();
}
}
twitter_init_settings();
On the frontend, where I am spitting out $tweets = twitter_feed()->output_feed(); (with a foreach loop afterwards) I am getting an Uncaught Exception error. Oddly, it shows the custom message, 'test', so it must know about my exception, so why is it saying it is uncaught?
Uncaught Exception error happen while an exception is not catched (in try catch statements)
Remove the return statment because the catch might not be reached.
When i initiate a class which does not exist , It throws the error, I Don't want to halted by that error . So i try trycatch method , But it still giving me same error, Can someone explain why this error is not been catched
I tried
try{$obj = new classname();}
catch(Exception $e){ echo 'class does not exist, move on' ;}
Fatal error: Class 'classname' not found in C:\WampDeveloper\Websites\localhost\webroot\index.php on line 4
Can someone explain why this error can not be catched ?
Is their is another way to catch and handle this kind of errors ?
UPDATE
We can catch mysql fatal errors by try catch method , So don't say fatal errors can not be handeled by try catch method
Two ways to solve this, use a autoloader that runs a custom written function for each object that does not exist so you can try to "include" a file on demand.
function autoload($objname){
if(is_readable(($f = '/path/to/class/'.$objname.'.php'))){
include $f;
} else {
throw Exception("$f does not exist");
}
}
spl_autoload_register('autoload');
new classname(); // try to load /path/to/class/classname.php
Or you can upgrade to PHP 7 where the error logic has had little overhaul:
Hierarchy
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
So a code like this would work:
try{
$obj = new classname();
} catch(Error $er){
echo 'class does not exist, move on';
} catch(Exception $ex){
echo 'a custom exception has been thrown:' . $ex->getMessage();
} catch(Throwable $t){
// Obsolete code, as Throwables are either Error or Exception, that were caught above.
}
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');
Fatal error: Uncaught exception
'EppCommandsExceptions' with message
'Required parameter missing'
The line in question:
throw new EppCommandsExceptions($result->msg, $codigo);
Why am I having this error on this line?
On EppCommandsExceptions.class.php
I have this class that extends Exception:
class EppCommandsExceptions extends Exception
{
//could be empty.
}
Next, on CommandsController.php I have:
include_once('EppCommandsExceptions.class.php');
and, later, if something bad happens on method1:
throw new EppCommandsExceptions($result->msg, $codigo);
later, on this same controller, another method2 that will run after method1,
I have:
if something goes bad with this too:
throw new EppCommandsExceptions($result->msg, $codigo);
Later I have, for the contact part - method1
try
{
$createdContact = $comandos->createContact($contactoVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
And later, for domain part: method2
try
{
$createdDomain = $comandos->createDomain($domainVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Domain. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Is it because I'm using the same exception for both methods?
Should I have one Exception class for EACH method? :s
Please advice,
Thanks a lot.
MEM
The exception you throw will only be caught if it's inside a try block.
If it isn't it'll propagate up the call stack, until it is caught in one of the earlier calling functions.
You're getting that fatal error because the exception you throw is never caught, so it's handled by the default unhandled exceptions handler, which emits the fatal error.
Examples:
try
{
$createdContact = $comandos->createContact($contactoVo);
if (error_condition())
throw new EppCommandsExceptions $e;
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Throwing the exception directly in the try block is not usually very useful, because you could just as well recover from the error condition directly instead of throwing an exception. This construct becomes more useful, though, if createContact may throw an exception. In this case, you have at some point to catch EppCommandsExceptions to avoid a fatal error.