Laravel 框架返回状态拦截

 

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Http\Success;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
        // 拦截参数验证错误
        if($exception instanceof ValidationException)
        {
            $error_str = '';
            $error = $exception->errors();
            if(count($error))
            {
                foreach ($error as $v)
                {
                    $error_str = $v;
                }
            }
            return Success::success_v2(Success::params,$error_str,arrIsKey($error_str,0));

        }

        // 用户认证的异常,我们需要返回 401 的 http code 和错误信息 UnauthorizedHttpException
        if ($exception instanceof UnauthorizedHttpException) {
            return Success::success_v2(Success::auth);
        }

        // 拦截授权异常
        if($exception instanceof ModelNotFoundException)
        {
            return Success::success_v2(Success::auth);
        }

        // 拦截授权异常
        if($exception instanceof AuthorizationException)
        {
            return Success::success_v2(Success::auth);
        }


        return parent::render($request, $exception);
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值