傳送錯誤報告電子郵件
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>