Zi 字媒體
2017-07-25T20:27:27+00:00
Laravel Error Handling
PHP:7.2
Laravel:5.8
對於一個完整的框架來說,Error handling 是很重要的一環。
Laravel 提供了 App\Exceptions\Handler class 來處理所有專案中的 Exceptions。
Basic Usage
Laravel 在 Handler class 中定義了 report 及 render class,讓開發者針對不同情境處理 Exceptions。
app/Exceptions/Handler.php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
// 不要寫進 log 裡的 Exception
protected $dontReport = [
\Illuminate\Validation\ValidationException::class,
];
// 紀錄哪些資料不要被記錄進 flash 中
protected $dontFlash = [
'password',
'password_confirmation',
];
// 回報 Exception
public function report(Exception $exception)
{
// 針對 InvalidArgumentException 做處理
if ($exception instanceof \InvalidArgumentException) {
// do something
}
parent::report($exception);
}
// 將 Exception 顯示在網頁上
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}
Custom Exceptions
如果是自己定義的 Exception,也不需要一個一個去判斷,在上層的 Illuminate\Foundation\Exceptions\Handler 中,會去判斷並執行 Exception 中的 report() 及 render() 兩個 method,因此只要在自己的 Exception 中定義好 method 的內容就可以自動執行了。
app/Exceptions/CustomException.php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{
public function report()
{
// do something
}
public function render()
{
return response()->json([
'message' => $this->getMessage()
], 400);
}
}
Categories: Laravel
Tags: LaravelPHP
分類
Android
AngularJS
API Blueprint
Chrome
Database
MySQL
DataStructure
Editor
Vim
Firefox
Git
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋:
寫了
5860316篇文章,獲得
23313次喜歡