laravel 中自定义 api 接口的错误消息

当在laravel 中编写 api 接口时,throw new Exception() 返回的错误消息格式不是我们想要的格式

解决办法:

在 App\Exceptions目录下新建一个 ApiException类 继承 Exception 

namespace App\Exceptions;
 
class ApiException extends \Exception{
 
    public function __construct($message="")
    {
        parent::__construct($message);
    }
}

之后,laravel 的所有错误处理都是在 App\Exceptions\Handler.php中处理的

这个类中主要有两个方法 一个是 report   一个是render

report与我的的错误处理无关,我们在这里要改写一个 render方法

下面是render的原始方法
 

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
 
        return parent::render($request, $exception);
    }

在render中我们可以判断一下 $exception 是不是我们定义的 ApiException的一个实例,然后做相应的处理

代码如下:

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        //如果$exception 是 ApiException的一个实例,则自定义返回的错误信息
        if($exception instanceof ApiException){
            $result = [
                "code"=>422,
                "msg"=>$exception->getMessage(),
                "data"=>""
            ];
            return response()->json($result);
        }
        //如果不是,则使用 父类的处理方法
        return parent::render($request, $exception);
    }

此时,当在写 api接口的时候,如果想抛出一个错误,就可以使用 throw new ApiException("这是一个错误");

数据就会以 json格式返回错误信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值