欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Laravel統(tǒng)一錯誤處理為JSON的方法介紹

 更新時間:2020年10月18日 16:18:36   作者:13sai  
這篇文章主要給大家介紹了關于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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論