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

laravel框架 api自定義全局異常處理方法

 更新時(shí)間:2019年10月11日 16:45:47   作者:Miss_shy  
今天小編就為大家分享一篇laravel框架 api自定義全局異常處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

api返回實(shí)現(xiàn)

$result = User::find($id);
if(empty($result)){
  throw new ApiException('獲取失敗');
}
else{
  return json_decode($result);
}

api返回信息

{
  "msg": "",
  "data": "獲取失敗",
  "status": 0
}

1,添加異常類

namespace App\Exceptions;


class ApiException extends \Exception
{

  function _construct($msg='')
  {
    parent::_construct($msg);
  }

}

2,修改laravel異常類u。。。

namespace App\Exceptions;


public function render($request, Exception $e)
{
  if ($e instanceof ApiException){
    $result = [
      "msg" => "",
      "data"=>$e->getMessage(),
      "status"=>0
    ];
    return response()->json($result);
  }
  return parent::render($request, $e);

考慮開發(fā)配置時(shí)

public function render($request, Exception $e)
{
 
  if(config('app.debug')){
    return parent::render($request,$e);
  }
  return $this->handle($request,$e);
}

public function handle($request,Exception $e){
  if ($e instanceof ApiException){
    $result = [
      "msg" => "",
      "data"=>$e->getMessage(),
      "status"=>0
    ];
    return response()->json($result);
  }

  return parent::render($request, $e);
}

以上這篇laravel框架 api自定義全局異常處理方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論