大飞_dafei

导航

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

01) 添加异常处理类

02) 修改laravel 异常处理

03) 抛出异常

 

01) 添加异常处理类

<?php

//app/Exceptions/V1Exception.php
namespace App\Exceptions;


use Throwable;

class V1Exception extends \Exception
{
    function __construct(string $message = "", int $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}

02) 修改laravel 异常处理

//app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
    if ($exception instanceof V1Exception) {
        $result = [
            "msg"    => $exception->getMessage(),
            "data"   => '',
            "status" => 0
        ];
        return response()->json($result);
    }
    return parent::render($request, $exception);
}

03) 抛出异常

throw new V1Exception("我要抛出异常");

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

posted on 2020-10-14 09:39  大飞_dafei  阅读(770)  评论(0编辑  收藏  举报