1. 程式人生 > >laravel框架中引入全域性錯誤碼以及相關報錯資訊

laravel框架中引入全域性錯誤碼以及相關報錯資訊

project\config\errorcode.php
<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/9/6
 * Time: 10:28
 */

return [

    /*
    |--------------------------------------------------------------------------
    | customized http code
    |--------------------------------------------------------------------------
    |
    | The first number is error type, the second and third number is
    | product type, and it is a specific error code from fourth to
    | sixth.But the success is different.
    |
    */

    'code' => [
        200 => '成功',

        //單詞書
        310001 => '缺少必要的引數',
        310002 => '單詞書已經存在',
        310003 => '軟刪除失敗',
        310004 => '單詞書修改失敗',
        310005 => '軟刪除失敗,存在單詞列表',

        //單詞列表
        320001 => '缺少必要的引數',
        320002 => '單詞列已經存在',
        320003 => '單詞列排序變更失敗',
        320004 => '不存在的單詞列',
        320005 => '軟刪除失敗,存在單詞',
        320006 => '軟刪除失敗',
    ],

];

project\app\Http\Controllers\Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function success($data = [])
    {
        return response()->json([
            'status'  => true,
            'code'    => 200,
            'message' => config('errorcode.code')[200],
            'data'    => $data,
        ]);
    }

    public function fail($code, $data = [])
    {
        return response()->json([
            'status'  => false,
            'code'    => $code,
            'message' => config('errorcode.code')[(int) $code],
            'data'    => $data,
        ]);
    }
}