简体   繁体   中英

Disable throwing exceptions for E_USER_WARNING

Laravel is returning a 500 when I do:

trigger_error("Some message", E_USER_WARNING);

I need it to not error out, but I do want it to run through \\App\\Exceptions\\Handler::report which logs the warning to Sentry.

How do I disable turning warnings and errors into exceptions with Laravel 5.2?

You could edit laravel's error handler to only report warnings in 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;
    }
}

User Warning: Modifying vendor code is usually a bad idea.

You can avoid modifying vendor code by extending the HandleExceptions class and registering your new class in Kernel.php

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

Since you can't display the normal content of the page when you are inside the ErrorHandler, you have to throw another error message:

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

This will create a custom warning entry for sentry without throwing a real error in php that would stop your normal code.

you could also wrap it in a function

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

I think it should be handled by php. did you try error_reporting()? set_error_handler

more information:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM