当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel统一错误处理为JSON的方法介绍

发布:smiling 来源: PHP粉丝网  添加日期:2022-03-28 14:36:26 浏览: 评论:0 

Laravel中的AppExceptionsHandler 类负责记录应用程序触发的所有异常,这在我们开发过程中十分方便,总是try...catch使代码太过繁琐且可读性大大降低,那么怎么使用它处理异常为json呢?

方法如下:

我们可以新建一个class,用来处理异常返回。

  1. <?php 
  2. /** 
  3.  * Author: sai 
  4.  * Date: 2020/1/15 
  5.  * Time: 14:31 
  6.  */ 
  7.  
  8. namespace App\Exceptions; 
  9.  
  10.  
  11. class ApiException extends \Exception 
  12. { 
  13.  const ERROR_CODE = 1001; 
  14.  const ERROR_MSG = 'ApiException'; 
  15.  
  16.  private $data = []; 
  17.  
  18.  /** 
  19.   * BusinessException constructor. 
  20.   * 
  21.   * @param string $message 
  22.   * @param string $code 
  23.   * @param array $data 
  24.   */ 
  25.  public function __construct(string $message, string $code, $data = []) 
  26.  { 
  27.   $this->code = $code ? : self::ERROR_CODE; 
  28.   $this->message = $message ? : self::ERROR_MSG; 
  29.   $this->data = $data; 
  30.  } 
  31.  
  32.  /** 
  33.   * @return array 
  34.   */ 
  35.  public function getData() 
  36.  { 
  37.   return $this->data; 
  38.  } 
  39.  
  40.  /** 
  41.   * 异常输出 
  42.   */ 
  43.  public function render($request) 
  44.  { 
  45.   return response()->json([ 
  46.    'data' => $this->getData(), 
  47.    'code' => $this->getCode(), 
  48.    'messgae' => $this->getMessage(), 
  49.   ], 200); 
  50.  } 
  51. } 

然后我们在Handler加入,加入$dontReport,便不会使用自带的错误处理,而使用自定义的处理。

  1. <?php 
  2.  
  3. namespace App\Exceptions; 
  4.  
  5. use Exception; 
  6. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; 
  7.  
  8. class Handler extends ExceptionHandler 
  9. { 
  10.  /** 
  11.   * 一些不需管或不需要抛出的异常 
  12.   */ 
  13.  protected $dontReport = [ 
  14.   ApiException::class, 
  15.  ]; 
  16.  
  17.  ... 
  18. } 

我们测试一下:

  1. <?php 
  2.  
  3. namespace App\Http\Controllers; 
  4.  
  5. use App\Exceptions\ApiException; 
  6. use Illuminate\Http\Request; 
  7.  
  8. class HomeController extends Controller 
  9. { 
  10.  public function index(Request $request) 
  11.  { 
  12.   throw new ApiException('error', 10001, ['oh' => 'no']); 
  13.   return 1; 
  14.  } 
  15. } 

查看输出:

Laravel统一错误处理为JSON的方法介绍

测试ok,我们可以愉快的使用啦。当然,其他形式的错误输出可以自行扩展。

Tags: Laravel统一错误处理

分享到: