Laravel 任意位置响应请求,自定义接口异常处理类

Laravel 任意位置响应请求,自定义接口异常处理类

1.创建文件 app\Exception\ApiException.php

<?php


namespace App\Exceptions;


class ApiException extends \Exception
{
    function __construct($errorMsg='', $errorCode = 500)
    {
        $this->errorMsg = $errorMsg;
        $this->errorCode = $errorCode;
        parent::__construct($errorMsg);
    }
}

2.修改  app\Exception\Handler.php

 /**
     * 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);
        // 如果config配置debug为true ==>debug模式的话让laravel自行处理
//        if(config('app.debug')){
//            return parent::render($request, $exception);
//        }
        if($exception instanceof ApiException) {
            return $this->handle($request, $exception);
        }else{
            return parent::render($request, $exception);
        }

    }

    // 新添加的handle函数
    public function handle($request, Exception $e){
        // 只处理自定义的APIException异常
        if($e instanceof ApiException) {
            $result = [
                "msg" => $e->errorMsg,
                "code" => $e->errorCode
            ];
            return response()->json($result);
        }
        return parent::render($request, $e);
    }

使用

任意位置

if(empty($row)){
            throw new ApiException('规格不存在','201');
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值