1. 程式人生 > >Laravel 5.2 作為APP後端開發修改系統錯誤成返回json

Laravel 5.2 作為APP後端開發修改系統錯誤成返回json

因為專案原因沒辦法為了快速上手只有用PHP做後端開發,TP效率不咋樣 所以直接上手的laravel 5.2 但是感覺還是挺複雜的需要花時間研究.

因為程式出錯是難以避免的,畢竟一般很多開發都沒有專業的testing,app接受資料都是json格式,但是系統預設報錯會直接輸出html程式碼,如果app請求出錯必然會返回html程式碼無法識別,所以我吧系統預設的報錯修改了下,

先看看效果

修改後任何報錯都會用json 格式輸出:


沒修改前會直接輸出錯誤資訊,

APP_DEBUG設定false的時候還是會輸出html


懶得廢話了 直接點, 找了很久找到的輸出檔案

\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php

找到這個檔案裡面的函式  toIlluminateResponse  第123行

把裡面的程式碼替換為:

 protected function toIlluminateResponse($response, Exception $e)
    {
        if(config('app.debug'))
        {
            $response = new Response($response->getContent(), $response->getStatusCode(), $response->headers->all());

            $response->exception = $e;

            return $response;

        }
        else
        {
            $return_arr =array(
                'resultcode'=>500,
                'reason'=>'error',
                'result'=>array(
                    'data'=>array('reason'=>'伺服器端發生系統錯誤!','error_code'=>$response->getStatusCode(),'time'=>time()),
                ));
            $response = new Response($return_arr, 200, $response->headers->all());
            $response->exception = $e;
            return $response;
        }
    }

一眼就能看懂對吧? 你在測試開發的時候還是會照樣輸出錯誤資訊詳情,但是部署上線的時候就會輸出json資料  程式碼就自己修改了 需要什麼樣的自己改

每天遇到問題就記錄下 希望跟我一樣遇見這些問題的朋友們能有個解決方案