发送错误报告电子邮件

Laravel 中的异常由 App \ Exceptions \ Handler.php 处理

默认情况下,此文件包含两个函数。报告和渲染。我们只会使用第一个

 public function report(Exception $e)

报告方法用于记录异常或将其发送到 BugSnag 等外部服务。默认情况下,report 方法只是将异常传递给记录异常的基类。但是,你可以根据需要自由记录异常。

基本上这个函数只是转发错误而什么都不做。因此,我们可以插入业务逻辑以基于错误执行操作。在本例中,我们将发送包含错误信息的电子邮件。

public function report(Exception $e)
{
    if ($e instanceof \Exception) {
        // Fetch the error information we would like to 
        // send to the view for emailing
        $error['file']    = $e->getFile();
        $error['code']    = $e->getCode();
        $error['line']    = $e->getLine();
        $error['message'] = $e->getMessage();
        $error['trace']   = $e->getTrace();

        // Only send email reports on production server
        if(ENV('APP_ENV') == "production"){
            #1. Queue email for sending on "exceptions_emails" queue
            #2. Use the emails.exception_notif view shown below
            #3. Pass the error array to the view as variable $e
            Mail::queueOn('exception_emails', 'emails.exception_notif', ["e" => $error], function ($m) {
                $m->subject("Laravel Error");
                $m->from(ENV("MAIL_FROM"), ENV("MAIL_NAME"));
                $m->to("webmaster@laravelapp.com", "Webmaster");
            });

        }
    }

    // Pass the error on to continue processing
    return parent::report($e);
}

电子邮件的视图(“emailils.exception_notif”)如下所示

<?php 
$action = (\Route::getCurrentRoute()) ? \Route::getCurrentRoute()->getActionName() : "n/a";
$path = (\Route::getCurrentRoute()) ? \Route::getCurrentRoute()->getPath() : "n/a";
$user = (\Auth::check()) ? \Auth::user()->name : 'no login';
?>

There was an error in your Laravel App<br />

<hr />
<table border="1" width="100%">
    <tr><th >User:</th><td>{{ $user }}</td></tr>
    <tr><th >Message:</th><td>{{ $e['message'] }}</td></tr>
    <tr><th >Action:</th><td>{{ $action }}</td></tr>
    <tr><th >URI:</th><td>{{ $path }}</td></tr>
    <tr><th >Line:</th><td>{{ $e['line'] }}</td></tr>
    <tr><th >Code:</th><td>{{ $e['code'] }}</td></tr>
</table>