doushe8577
2017-09-29 05:42
浏览 119
已采纳

Laravel:记录错误,并显示一个很好的视图

I'm trying to log errors in Laravel but it throws the Chrome default 500 error page before even reaching the render function, how am I supposed to catch any errors?

I want to log all errors to the database and show a nice user friendly CUSTOM view but it how can I when it doesn't make it to the render method?

Laravel doesn't make it to:

public function render($request, Exception $exception)

So how are you meant to log errors? This seems wrong in so many ways.

public function render($request, Exception $exception)
{
    if (strlen($exception->getMessage()) > 0) {
        $agent = new Agent();
        $errorLog = new ErrorLog;
        $errorLog->error_message = $exception->getMessage();
        $errorLog->error_file = $exception->getFile();
        $errorLog->error_line = $exception->getLine();
        $errorLog->request_ip = $request->ip();
        $errorLog->request_url = $request->root();
        $errorLog->request_device = $agent->isDesktop() ? 'Desktop' : ($agent->isMobile() ? 'Mobile' : 'Tablet');
        $errorLog->request_system = $agent->platform() . ' ' . $agent->version($agent->platform());
        $errorLog->request_browser = $agent->browser();
        $errorLog->error_happened_to = (Auth::check() ? Auth::user()->username : 'Guest');
        $errorLog->save();
    }

    return parent::render($request, $exception);
}

Also, my .EVN file:

APP_NAME=Laravel
APP_ENV=local
APP_KEY=*************************************************
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=************
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douxianji3367 2017-09-29 08:35
    已采纳

    This is how I handle the same issue. In app/Exceptions/Handler.php:

    public function report(Exception $exception)
    {
        if(!config('app.debug')) {
            if ($this->shouldReport($exception)) {
                $this->logError($exception);
            }
        }
        if(env('APP_ENV') == 'local'){
            parent::report($exception);
        }
    }
    
    public function render($request, Exception $exception)
    {
        if(!config('app.debug')) {
            if($this->shouldReport($exception)){
                return response()->view('errors.500', compact('exception'));
            }
        }
        return parent::render($request, $exception);
    }
    

    I added a function logError that writes the error to the database, and I have a template in resources/views/errors - 500.blade.php - that has a custom error page.

    I also use the APP_DEBUG in the .env to determine whether to log the error to the database and display the error page or to show the error details on screen.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题