Laravel 如何处理 PHP 警告?

2022-01-17 00:00:00 exception ldap php laravel

我正在尝试使用 Laravel 连接到 LDAP 服务器.重要的是要说我正在使用 PHP 函数 ldap_connectldap_bind 而不是使用包来处理它.

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.

关键是当我提供错误的用户名和密码时,ldap_bind 函数会给我们一个 PHP 警告.我可以接受这个警告,并且正如文档中所述,当绑定没有发生时,该函数返回 false.

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.

但是,当这个警告被触发时,Laravel 会抛出一个异常.这不是异常,Laravel 不应该抛出异常,我不想将其作为异常处理;我只需要构建一个 if 条件,它将向用户返回一条消息.

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.

Laravel 是否将所有警告都视为异常?

Does Laravel catch all warnings as an Exception?

推荐答案

这是 Laravel 的预期行为.Laravel 会将任何错误转换为 ErrorException 实例.这是 bootstrap() 方法L42" rel="nofollow noreferrer">Illuminate/Foundation/Bootstrap/HandleExceptions.php 类.

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');
    }
}

error_reporting(-1); 将设置 PHP 报告所有错误(阅读更多 这里).

The error_reporting(-1); will set PHP to report all errors (read more here).

虽然这部分代码:

set_error_handler([$this, 'handleError']);

将设置自定义错误处理程序.如果检查 handleError() 方法,很明显 Laravel 会将任何错误转换为 ErrorException 实例.

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. :)

相关文章