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,便不会应用自带的错误处理,而应用自定义的解决。

<?phpnamespace App\Exceptions;use Exception;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;class Handler extends ExceptionHandler{    /**     * 一些不需管或不须要抛出的异样     */    protected $dontReport = [        ApiException::class,    ];    ...}

咱们测试一下:

<?phpnamespace 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,咱们能够欢快的应用啦。当然,其余模式的谬误输入能够自行扩大。