Laravel-自定義API返回的JSON格式


按照我司規范,服務器處理http請求后返回的JSON,應該是這樣的格式:

{
    code: 
    data:  
    msg: 
}

這就需要對Laravel框架默認的返回值(太隨意了,缺少一個統一的結構來包裝返回值)做一些處理,具體包括以下幾個部分:

(一)使用LaravelResponse Macro機制來自Controller的直接返回

需要進行以下幾步操作:

1、創建一個ServiceProvider

php artisan make:provider ResponseMacroServiceProvider
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Response; class ResponseMacroServiceProvider extends ServiceProvider { public function boot() { Response::macro('horesp', function ($code=2000, $data=null, $msg=null) { $content = array( 'code' => $code, 'data' => $data, 'msg' => $msg ); return response()->json($content); }); } public function register() { //  } }

 

2、在config/app.php文件中的‘providers’列表中,增加下面的一行

App\Providers\ResponseMacroServiceProvider::class,

 

3、創建一個HOBaseController,以后所有的Controller都繼承這個類

php artisan make:controller HOBaseController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller; class HOBaseController extends Controller {
  //這個方法只應該在接口順利完成了對請求業務的處理之后調用 public function response($data=null, $msg=null) { return response()->horesp(2000, $data, $msg); } }

  4、以后在controller類里面直接返回結果時,使用這個方式

return $this->response($user->name);

 

(二)對主動返回的錯誤值做處理

原理是通過主動拋出異常,來處理所有需要返回錯誤代碼和錯誤信息的情況,由框架的異常處理機制來構造最終的返回值。 

1、創建一個HOException類

php artisan make:exception HOException

2、在App\Exception文件夾中,創建一個HOError.php文件,對每一個錯誤,都定義一個方法,供外部調用。

<?php
namespace App\Exceptions;
use \App\Exceptions\HOException as HOException; class HOError { public function generalErr() { throw new HOException('General Error Occurred', 2001); } }

3、在HOBaseController里面,增加如下代碼

protected $error;
public function error() { $this->error = new HOError(); return $this->error; }

4、在App/Exeption/Handler.php文件中,重寫render方法

use Illuminate\Support\Facades\Log;
use \App\Exceptions\HOException as HOException; use Illuminate\Http\Exceptions\HttpResponseException; public function render($request, Exception $exception) { //對詳細的錯誤信息,進行記錄,但是不返回給前端 Log::debug( parent::render($request, $exception) ); if ( $exception instanceof HOException ) { $msg = $exception->getMessage(); }else{ $msg = 'Server Bad'; } return response()->horesp( $exception->getCode(), null, $msg); }

 5、在Controller的方法里,可以這樣來返回錯誤碼和錯誤信息

return $this->error()->generalErr();

(三) 對Validate不通過的情況做處理

創建一個HOFormRequest類,繼承FormRequest類,以后創建FormRequest,都從HOFormRequest類去集成. 解決方案來自:https://www.jianshu.com/p/658f979abfb7

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest; use App\Exceptions\HOException as HOException; use Illuminate\Contracts\Validation\Validator as Validator; class HOFormRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ //  ]; } protected function failedValidation(Validator $validator) { $message = $validator->errors()->all(); throw new HOException(implode($message), 3000); } }

 

(四)對Authenticate不通過情況的處理

1、創建一個unauthenticated路由,在對應的controller方法中返回標准格式的錯誤信息和字符串給客戶端。

Route::post('/user/unauthenticated', 'Api\UserController@unauthenticated')->name('unauthenticated');

2、修改app\middleware\authenticate.php中間件的redirectTo方法

protected function redirectTo($request){
    return route('unauthenticated');
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM