为 E_USER_WARNING 禁用抛出异常

Disable throwing exceptions for E_USER_WARNING

当我这样做时,

Laravel 返回 500:

trigger_error("Some message", E_USER_WARNING);

我需要它 而不是 出错,但我 希望它 运行 到 \App\Exceptions\Handler::report它将警告记录到 Sentry。

如何禁用 Laravel 5.2 将警告和错误转换为异常?

我觉得应该由php来处理。你试过error_reporting()了吗? set_error_handler

更多信息:

Out of the box, Laravel supports writing log information to single files, daily files, the syslog, and the errorlog. To configure which storage mechanism Laravel uses, you should modify the log option in your config/app.php configuration file. For example, if you wish to use daily log files instead of a single file, you should set the log value in your app configuration file to daily

laravel error and logging

由于在ErrorHandler内部无法正常显示页面内容,只好再抛出一个错误信息:

Route::get('error', function() {
    $client = new Raven_Client(env("SENTRY_DSN"));
    $client->captureMessage("Some Warning", ['log'], [
        'level' => 'warning'
    ]);
});

这将为 sentry 创建一个自定义警告条目,而不会在 php 中引发真正的错误,从而停止您的正常代码。

你也可以将它包装在一个函数中

function trigger_sentry_warning($message) {
    $client = new Raven_Client(env("SENTRY_DSN"));
    $client->captureMessage($message, ['log'], [
        'level' => 'warning'
   ]);
}

您可以编辑 laravel 的错误处理程序以仅在 HandleExceptions.php

中报告警告
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
    $exception = new ErrorException($message, 0, $level, $file, $line);

    if (E_USER_WARNING & $level) {
        $this->getExceptionHandler()->report($exception);
    }
    elseif (error_reporting() & $level) {
        throw $exception;
    }
}

用户警告:修改供应商代码通常不是一个好主意。

您可以通过扩展 HandleExceptions class 并在 Kernel.php

中注册新的 class 来避免修改供应商代码
MyHandleExceptions extends HandleExceptions {
    public function handleError($level, $message, $file = '', $line = 0, $context = [])
    {   
        if (E_USER_WARNING & $level) {
            $this->getExceptionHandler()->report(new ErrorException($message, 0, $level, $file, $line));
        }
        else {
            return parent::handleError($level, $message, $file, $line, $context);
        }
    }
}