Slim 4 error handling not catching base Exception - php

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

Related

how to generate a 403 error in the Debian 10 logs from my authentication form with symfony 5.4

I host my web application on Debian 10 using symfony 5.4.
Users must authenticate to access my application.
I would like to know if it is possible to generate a 403 error in the Debian logs (/var/log/apache/access.log or elsewhere) in case of bad credentials ?
For the moment, the logs show a 'POST 302' error which does not suit me.
For symfony experts, I use loginFormAuthenticator extends AbstractLoginFormAuthenticator.
I don't know where I should do this. If it's on the server or in my application?
here is what i tried
namespace Symfony\Component\Security\Http\Authenticator;
abstract class AbstractLoginFormAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface, InteractiveAuthenticatorInterface{
...
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response{
...
return new RedirectResponse($url, 403, ['HTTP/1.0 403 Forbidden']);
Thanks for your feedback.
You cannot redirect with a code, the code is ignored because the redirection itself relies on a code in the 300 range (302 in this case).
If you want to give an error response, you can just throw $exception;, but there will be no redirect.
However, the application log should already contain the authentication failure. It's located in /path/to/app/var/log/prod.log or whatever environment you happen to be running instead of prod.
If you do want to log to the system logs, you can use php error_log function.

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.

Cannot debug Laravel HTTP Tests

I have a couple of HTTP tests in a Laravel 5.6 project. I would like to debug the tests and the codepath they call. I can debug the test method but not the actual code. Meaning the debugger doesn't stop at breakpoints in the controller etc.
I'm using Xdebug 2.6.0, PhpStorm 2018.1 and PHP 7.2.
It turns out that the 500 error code came from one of the custom middleware layers and not from the controller. So the breakpoint never got hit because of the error in the middleware layer. I wish that there was an error stack trace instead of only the message "Expected status code 200 but received 500".
I ended up mocking the middleware. Just in case someone is interested how I did it:
$mockMiddleware = Mockery::mock("App\Http\Middleware\MyMiddleware");
$mockMiddleware->shouldReceive("handle")->once()
->andReturnUsing(function ($request, $next) {
return $next($request);
});
App::instance("App\Http\Middleware\MyMiddleware", $mockMiddleware);

Yii2 - error handler can not catches database exceptions

I'm working on Yii2 advanced application project and I have a problem with yii2 built-in Error Handler. Here is description of my problem:
I have set errorAction in my backend configuration in this way:
'errorHandler' => [
'errorAction' => 'site/error',
],
Now, the method actionError() in the SiteController catches every application exceptions, user defined exceptions and also fatal errors, except database related exception such as yii\db\IntegrityException. I don't know why, but when such an exception occurs, actionError() does not do anything! I don't want to catch exception manually with try-catch block and I want the central ErrorHandler catches all exception.
How can I fix this problem? Thank you all specially yii experts for paying attention. Please help me to solve this strange problem.
According to this GitHub issue: yiisoft/yii2/issues/10657 and to the comment made by #Yupik you must change the YII_DEBUG.
If YII_DEBUG is true, you should see proper message about yii\db\IntegrityException in debug mode.
If YII_DEBUG is false(like in a production enviroment) error is redirected to actionError() and see it in a user-friendly mode.

ZF2 PHP Exception

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.

Categories