Laravel統(tǒng)一錯誤處理為JSON的方法介紹
Laravel中的AppExceptionsHandler 類負責記錄應用程序觸發(fā)的所有異常,這在我們開發(fā)過程中十分方便,總是try...catch使代碼太過繁瑣且可讀性大大降低,那么怎么使用它處理異常為json呢?
方法如下:
我們可以新建一個class,用來處理異常返回。
<?php /** * Author: sai * Date: 2020/1/15 * Time: 14:31 */ namespace App\Exceptions; class ApiException extends \Exception { const ERROR_CODE = 1001; const ERROR_MSG = 'ApiException'; private $data = []; /** * BusinessException constructor. * * @param string $message * @param string $code * @param array $data */ public function __construct(string $message, string $code, $data = []) { $this->code = $code ? : self::ERROR_CODE; $this->message = $message ? : self::ERROR_MSG; $this->data = $data; } /** * @return array */ public function getData() { return $this->data; } /** * 異常輸出 */ public function render($request) { return response()->json([ 'data' => $this->getData(), 'code' => $this->getCode(), 'messgae' => $this->getMessage(), ], 200); } }
然后我們在Handler加入,加入$dontReport,便不會使用自帶的錯誤處理,而使用自定義的處理。
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * 一些不需管或不需要拋出的異常 */ protected $dontReport = [ ApiException::class, ]; ... }
我們測試一下:
<?php namespace App\Http\Controllers; use App\Exceptions\ApiException; use Illuminate\Http\Request; class HomeController extends Controller { public function index(Request $request) { throw new ApiException('error', 10001, ['oh' => 'no']); return 1; } }
查看輸出:
測試ok,我們可以愉快的使用啦。當然,其他形式的錯誤輸出可以自行擴展。
總結
到此這篇關于Laravel統(tǒng)一錯誤處理為JSON的文章就介紹到這了,更多相關Laravel統(tǒng)一錯誤處理為JSON內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
php檢測網(wǎng)頁是否被百度收錄的函數(shù)代碼
下面給出一段php函數(shù),功能是檢測一個網(wǎng)頁是否被百度收錄,直接給出代碼2013-10-10Zend Framework實現(xiàn)具有基本功能的留言本(附demo源碼下載)
這篇文章主要介紹了Zend Framework實現(xiàn)具有基本功能的留言本,結合實例形式較為詳細的分析了Zend Framework實現(xiàn)留言本的具體步驟與相關實現(xiàn)技巧,需要的朋友可以參考下2016-03-03