2017-10-07 122 views
1

我想捕捉laravel錯誤,警告消息。我不想從config/app.php文件中禁用它們。我正在使用monolog來記錄一些信息。 這是我的一段代碼:防止laravel消息顯示並將用戶重定向到Laravel 5中的自定義頁面問題

public function view($id){ 
    try { 
    $tag = Tags::find(12313); // tags is a model 
    }catch(Exception $error){ 
     echo 'error'; exit(); 
     $this->log->logMessage(Logger::ERROR, $error->getMessage()); 
     return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']); 
    } 
} 

$this->log是一類,我現在用的是monolog class日誌信息。

事實是,現在它不會進入捕捉部分。我沒有收到error消息。我從laravel得到這個消息:

Trying to get property of non-object (View: ...... 

我故意把人數12313那裏,看看它是否工作。由於某種原因,不工作,我沒有重定向。這個想法,如果發生了什麼事情,我想重定向用戶到一個具有一般錯誤信息的特定頁面。我怎樣才能做到這一點?

+0

可以顯示日誌類,如果這是你自己的類 – iCoders

+0

@iCoders沒關係我的日誌類的內容,你可以看到我不在'exit()'函數之前沒有得到'error'消息:) – Chester

+0

我不是在尋找一個特定的案例,我想要一個普通的案例來捕獲所有的laravel錯誤信息,並將用戶重定向到一個特定的頁面。這只是很多情況下的一個例子:) – Chester

回答

0

你可以做到這一點在laravel。你可以處理應用程序\例外erors \ Handler類

public function render($request, Exception $exception) 
    { 

     if($exception instanceof NotFoundHttpException) 
     { 
      return response()->view('errors.404', [], 404); 
     } 
      if ($exception instanceof MethodNotAllowedHttpException) 
     { 
       return response()->view('errors.405', [], 405); 

     } 
     if($exception instanceof MethodNotAllowedHttpException) 
     { 

      return response()->view('errors.404', [], 405); 
     } 

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

和我應該在哪裏添加此功能? – Chester

+0

如果你在你的laravel中檢查App \ Exceptions \文件夾。你有Handler類文件 – iCoders

+0

app - > Exceptions-> handler.php – iCoders

0

find()方法不拋出一個異常,如果沒有找到記錄。所以這樣做,而不是:

public function view($id) 
{ 
    $tag = Tags::find(12313); // tags is a model 

    if (is_null($tag)) { 
     $this->log->logMessage(Logger::ERROR, $error->getMessage()); 
     return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']); 
    } 
} 

或者使用findOrFail()將拋出一個異常,如果沒有找到指定的記錄。

有時您可能希望在找不到模型時拋出異常。這在路由或控制器中特別有用。 findOrFail和firstOrFail方法將檢索查詢的第一個結果;但是,如果沒有找到結果,一個Illuminate\Database\Eloquent\ModelNotFoundException將被拋出

相關問題