Laravel自定义Api接口全局异常处理

在做API时,需要对一些异常进行全局处理,比如添加用户执行失败时,需要返回错误信息

  1. // 添加用户 www.bcty365.com 
  2. $result = User::add($user); 
  3. if(emptyempty($result)){ 
  4.     throw new ApiException('添加失败'); 
  5.  
  6. API 回复 
  7.     "msg" : "添加失败"
  8.     "data" : ""
  9.     "status" : 0 // 0为执行错误 

那么我们就需要添加一个全局异常处理,专门用来返回错误信息

步骤

1.添加异常处理类
2.修改laravel异常处理

1.添加异常处理类

  1. ./app/Exceptions/ApiException.php 
  2. <?php 
  3. namespace App\Exceptions; 
  4.  
  5. class ApiException extends \Exception 
  6.     function __construct($msg=''
  7.     { 
  8.         parent::__construct($msg); 
  9.     } 

2.修改laravel异常处理
  1. ./app/Exceptions/Handler.php 
  2.  
  3. // Handler的render函数 
  4. public function render($request, Exception $e
  5.     // 如果config配置debug为true ==>debug模式的话让laravel自行处理 
  6.     if(config('app.debug')){ 
  7.         return parent::render($request$e); 
  8.     } 
  9.     return $this->handle($request$e); 
  10.  
  11. // 新添加的handle函数 
  12. public function handle($request, Exception $e){ 
  13.     // 只处理自定义的APIException异常 
  14.     if($e instanceof ApiException) { 
  15.         $result = [ 
  16.             "msg"    => ""
  17.             "data"   => $e->getMessage(), 
  18.             "status" => 0 
  19.         ]; 
  20.         return response()->json($result); 
  21.     } 
  22.     return parent::render($request$e); 

这样就可以了

猜你喜欢

转载自blog.csdn.net/sunjinyan_1/article/details/80927820