1. 程式人生 > 程式設計 >Laravel統一錯誤處理為JSON的方法介紹

Laravel統一錯誤處理為JSON的方法介紹

Laravel中的AppExceptionsHandler 類負責記錄應用程式觸發的所有異常,這在我們開發過程中十分方便,總是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;
 }
}

檢視輸出:

Laravel統一錯誤處理為JSON的方法介紹

測試ok,我們可以愉快的使用啦。當然,其他形式的錯誤輸出可以自行擴充套件。

總結

到此這篇關於Laravel統一錯誤處理為JSON的文章就介紹到這了,更多相關Laravel統一錯誤處理為JSON內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!