【问题标题】:(Laravel 5.8) How to get verbosity level inside Exception Handler class(Laravel 5.8)如何在异常处理程序类中获取详细级别
【发布时间】:2019-10-17 23:32:58
【问题描述】:

我正在尝试获取异常处理程序类内部的详细级别,以便我可以打印更多或更少的信息。

我正在编写一个运行数十万次循环的批处理脚本,因此我的目标是限制堆栈跟踪的详细程度,因为在这种情况下,唯一有用的跟踪是最后 3 或 4 个。

我已经尝试过 SO 中给出的其他一些答案,并且已经阅读了整个互联网,但没有人谈论在异常处理程序中工作。 看起来更近的是this answer,它声明了$this->getOutput()->getVerbosity();,但这在错误处理程序中不起作用。

这是我的代码:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Mail;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use App\Mail\ExceptionOccured;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Output\OutputInterface;

class Handler extends ExceptionHandler 
...
...
public function render($request, Exception $e)
    {
        // return parent::render($request, $e);
        Log::error($this->buildMessage($e));
    }


    public function buildMessage($e) 
    {
        $verbosity_level = $this->getOutput()->getVerbosity();
        $is_verbose = ($verbosity_level >= OutputInterface::VERBOSITY_DEBUG);

        $t0 = $e->getTrace()[0];
        $tm = "Error: [{$e->getCode()}] {$e->getMessage()} @ {$t0['file']}:{$t0['line']}".PHP_EOL;
        // if ($is_verbose){
            ...(more code) ...
        // }
        return $tm;
    }
}

这是输出:

PHP Fatal error:  
Uncaught Error: Call to undefined method App\Exceptions\Handler::getOutput() in ...\Handler.php:89

我看到output 属性存在,但它受到保护并且没有getter。 也许引用的答案对早期版本有效。 我真的很迷茫,因为我只有 2 个月的时间玩 Laravel。

【问题讨论】:

    标签: laravel error-handling


    【解决方案1】:

    异常处理程序有一个特定的控制台方法:renderForConsole()

    /**
     * Render an exception to the console.
     *
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
     * @param  \Exception  $e
     * @return void
     */
    public function renderForConsole($output, Exception $e)
    {
        (new ConsoleApplication)->renderException($e, $output);
    }
    

    它是一个非常简单的 Symfony 控制台组件默认异常处理程序的包装器。根据您的需求定制!

    【讨论】:

      猜你喜欢
      • 2014-04-28
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多