问题
I'm trying to connect to a LDAP server using Laravel. It is important to say that I'm using the PHP functions ldap_connect
and ldap_bind
instead of using a package to handle it.
The point is that when I provide wrong user and password, the ldap_bind
function gives to us a PHP warning. I'm OK with this warning and, as is in the documentation, the function returns false when the bind does not occur.
But, Laravel is throwing an exception when this warning is triggered. This is not an exception, Laravel should not throw an exception and I wouldn't like to handle this as an exception; I just have to build an if
condition that will return a message to the user.
Does Laravel catch all warnings as an Exception?
回答1:
This is the intended behavior for Laravel. Laravel will turn any error into an ErrorException
instance. Here's the bootstrap()
method inside the Illuminate/Foundation/Bootstrap/HandleExceptions.php class.
public function bootstrap(Application $app)
{
$this->app = $app;
error_reporting(-1);
set_error_handler([$this, 'handleError']);
set_exception_handler([$this, 'handleException']);
register_shutdown_function([$this, 'handleShutdown']);
if (! $app->environment('testing')) {
ini_set('display_errors', 'Off');
}
}
The error_reporting(-1);
will set PHP to report all errors (read more here).
While this part of code:
set_error_handler([$this, 'handleError']);
Will set a custom error handler. If you check the handleError()
method, it's pretty clear that Laravel will turn any error into an ErrorException
instance.
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
}
Read more about user-defined error handler here.
Hope this clear things up. :)
回答2:
Not sure exactly the reason because I didn't write it but I assume having it work this way makes logging much easier.
Warnings get logged in php's error log but it's not possible to pass additional information along with it as context.
If that warning gets turned into an exception though, then you can pass the exception to the logger as well as other information such as the route which was hit, the request variables, etc... and log everything together. You also get to dictate the severity of the issue by designating it as log, debug, info, notice, warning, error, critical, alert, and emergency and through monolog, handle each of those as you see fit. This creates a log which is much easier to read and makes your code much easier to debug.
Additionally, as others have pointed out, it also allows you to do your work in try catch blocks which I believe also creates neater and cleaner code than trying to check if some variable === false
来源:https://stackoverflow.com/questions/40548258/how-laravel-handles-php-warnings