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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

13sai   2020-10-18 我要评论

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

方法如下:

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

<?php
/**
 * Author: sai
 * Date: 2020/1/15
 * Time: 14:31
 */

namespace App\Exceptions;


class ApiException extends \Exception
{
 const ERROR_CODE = 1001;
 const ERROR_MSG = 'ApiException';

 private $data = [];

 /**
  * BusinessException constructor.
  *
  * @param string $message
  * @param string $code
  * @param array $data
  */
 public function __construct(string $message, string $code, $data = [])
 {
  $this->code = $code ? : self::ERROR_CODE;
  $this->message = $message ? : self::ERROR_MSG;
  $this->data = $data;
 }

 /**
  * @return array
  */
 public function getData()
 {
  return $this->data;
 }

 /**
  * 异常输出
  */
 public function render($request)
 {
  return response()->json([
   'data' => $this->getData(),
   'code' => $this->getCode(),
   'messgae' => $this->getMessage(),
  ], 200);
 }
}

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

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
 /**
  * 一些不需管或不需要抛出的异常
  */
 protected $dontReport = [
  ApiException::class,
 ];

 ...
}

我们测试一下:

<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use Illuminate\Http\Request;

class HomeController extends Controller
{
 public function index(Request $request)
 {
  throw new ApiException('error', 10001, ['oh' => 'no']);
  return 1;
 }
}

查看输出:

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

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们