ZF2 PHP Exception - php

I'm building an application with ZF2.
I use ajax to POST some data on the application and when I trhrow a new Exception with this line:
throw new \Exception("Not Loged In.", 401);
The problem is everytime I throw a new error it returns a 500 even if I put anything as a second parameter of the exception.
Can anyone help me?
Thanks!

From zend framework's request lifecycle perspective every uncaught exception is an application error. You need a mechanism to convert that exceptions to meaningful HTTP responses before the framework convert them to an HTTP 50X for you.
For example, in your controller you can try something like below:
try {
$this->myService->tryToDoSomethingThatNeedsAuthentication();
} catch(AuthRequiredException $e) {
$this->getResponse()->setStatusCode($e->getCode()) // Assuming its 401
->setReasonPhrase($e->getMessage());
return;
} catch(\Exception) {
// handle other exceptions here
}

Problem is in your php configuration. Default Apache (or other server) hide details of your internal errors, so is returned short info:
Error 500 - internal server error
You must enable error_reporting:
in PHP:
http://php.net/manual/pl/function.error-reporting.php
or in php.ini in Apache configuration, and in .htaccess file it's possible. For developer's work you should show all errors.

Related

PHP - Laravel error : Symfony\Component\Finder\Exception\DirectoryNotFoundExceptionon my cPanel

I mistakenly ran my laravel application on debug mode in my production environment, and it threw an error for me to change App_debug:true to App_debug:false, which I did, ever since then, my site has been throwing an HTTP ERROR 500
"This page isn’t working admin.robyhub.com is currently unable to handle this request.
HTTP ERROR 500"
I then went on to my cpanel terminal and tried to clear the logs on the config file but it gives me the below error.
[thehcerl#premium261 admin.robyhub.com]$ php artisan config:clear
Symfony\Component\Finder\Exception\DirectoryNotFoundException
The "/home/thehcerl/admin.robyhub.com/resources/lang/ha" directory does not exist.
at vendor/symfony/finder/Finder.php:590
586▕ } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) {
587▕ sort($glob);
588▕ $resolvedDirs = array_merge($resolvedDirs, array_map([$this, 'normalizeDir'], $glob));
589▕ } else {
➜ 590▕ throw new DirectoryNotFoundException(sprintf('The "%s" directory does not exist.', $dir));
591▕ }
592▕ }
593▕
594▕ $this->dirs = array_merge($this->dirs, $resolvedDirs);
+2 vendor frames
3 app/Providers/TranslationServiceProvider.php:40
Illuminate\Support\Facades\Facade::__callStatic()
4 app/Providers/TranslationServiceProvider.php:27
App\Providers\TranslationServiceProvider::phpTranslations()
Cpanel Terminal
Ever since I changed debug to false on my .env from my laravel project main directory because the laravel documentation warned me to not use debug mode on a non-local environment. I expected my application would automatically stop receiving the laravel debug config solutions and would run properly.
This is not a very generic error, it's as a result of an error on my part, I created language folders that I did not link to my PHP "translationProvider.php" file, so it invariably gave me that issue.
I was using a purchased template from Envato so I hadn't taken the time to get the full inner working of the backend at the time.
If anyone has a similar error I hope this will guide you not to make the mistakes I made, and meticulously look through your code when making changed or edits.
Thanks, happy coding.

Catch HTTP client errors in Laravel 8

How do you catch errors thrown by the HTTP client (for example a time out) so that it doesn't throw the curl error in the Laraval debugger (in debug mode) before you can do anything with the error to avoid stopping the execution?
use Illuminate\Support\Facades\Http;
try {
$request = Http::post('https://example.com/post', [
'password' => 'guest']);
} catch(ConnectException $e)
{
//log error
}
//continue with another mode
Instead, I'm always getting the Laravel's Ignition error page
Illuminate\Http\Client\ConnectionException
cURL error 28: Failed to connect to example.com port 443: Timed out
and the error is not caught by my code. Is it possible that the laravel debugger always have priority and can't be overridden in debug mode?
This is almost certainly a namespacing issue.
You'll need either this at the top of the file:
use Illuminate\Http\Client\ConnectionException;
or do this:
} catch(\Illuminate\Http\Client\ConnectionException $e)
Otherwise, you're actually trying to catch something in the current namespace named ConnectionException (i.e. something like App\Controllers\ConnectionException), which will never exist.

Slim 4 error handling not catching base Exception

For some reason, my Slim 4 application error handler did not catch errors which can be caught by \Exception and I see 502 bad gateway error in the browser , here is my ErrorMiddleware configuration (I'm using PHP-DI to configure it ):
$definitions[ErrorMiddleware::class] = static function(ContainerInterface $container): ErrorMiddleware {
$middleware = new ErrorMiddleware(
$container->get(CallableResolverInterface::class),
$container->get(ResponseFactoryInterface::class),
(bool)$container->get(Config::class)->get('main.debug'), //false or true
true,
true
);
$middleware->setErrorHandler(HttpNotFoundException::class, $container->get(NotFoundHandler::class));
return $middleware;
};
I tried to add handler to handle 500 error like this $middleware->setErrorHandler(HttpInternalServerErrorException::class, $container->get(NotFoundHandler::class) );
but it's not working and I still see 502 bad gateway until I surround all controller action with try/catch(\Exception $e).
Do I need to add some other error handlers?? It's not clear for me how to correctly setup up handling in a slim 4 application.
Updated: I found that slim ErrorMiddleware by default catching slim HttpException which is extending Exception, but why not direclty Exception or even Throwable to gracefully exit application with nice error page
Okay it's my bad, adn everithing is fine with a slim, it's failing in the 'log_error()' fucntion as ErrorMiddlware is configured to log the error, but I did not install and configure Monolog yet, so it write logs to php-fpm logs and nginx alongside throwing 502 error

Why does geoip throw an exception?

Why this code:
geoip_country_code_by_name('unknown');
generate ErrorException, when must return false ?
This is a bug in GeoIP package and is not fixed in any release (<= 1.0.8). It's fixed in the trunk however (see this revision). You can solve this by compiling the source from the latest trunk.
Edited: thanks to Wrikken for pointing out how Laravel handles errors.
With GeoIP <= 1.0.8 geoip_country_code_by_name will trigger an error (E_NOTICE) whenever the name cannot be found. Laravel will always set error_reporting to -1 and handle all errors (even notices) and translate them into ErrorExceptions. Normally one can catch ErrorExceptions using a try-catch block, but in this case it is not possible because Laravel never throws the exception, it just translate it for displaying and logging purposes.
It is possible to ignore the error with the #-operator. It's a bit bad to do so since it will ignore all errors that the function might throw. In this case however, the only other error geoip_country_code_by_name can trigger is warning when the database can't be reached. Therefore you can safely ignore the error if you make sure the database is available: (Code not tested)
if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
{
#geoip_country_code_by_name('unknown');
}
else
{
// Throw exception or handle the error
throw new Exception(
"Required database not available at " .
geoip_db_filename(GEOIP_COUNTRY_EDITION)
);
}
Edit:
Laravel now throws the ErrorException so that one can catch it using a try-catch block. At the time of writing, this change is not yet in any released tag. But a catching errors will probably work with Laravel/Framework >= 4.0.8.
In 1.1.0 module version bug fixed https://pecl.php.net/package-changelog.php?package=geoip&release=1.1.0

ZF Error Handler not working

I'm trying to set up custom error handling, so I setup an ErrorController.php file within the default module, under the controllers directory. However, when I try to go to access an invalid controller, an error is shown that an uncaught exception occurred. This bypasses the ErrorController file though, and when I print the contents of the response object, it does not show any exceptions. Does anyone know what I might be doing wrong here? Cheers!
Ok I fixed the issue, apparently all I needed to do was add the following code: $front->throwExceptions(false);

Categories