美文网首页
Laravel 中自定义异常处理

Laravel 中自定义异常处理

作者: 骑代码奔小康 | 来源:发表于2019-09-25 13:42 被阅读0次

在学习JWT的时候,在中间件中token出现异常的时候一般是通过laravel自带的ExceptionHandler来抛出异常,那么在接口出现异常的时候我们想自己根据不同的错误定义异常呢,下面开始拙劣的表演:

API异常处理文件

在目录app\Exceptions下有个Handler.php文件,这里先不动,新创建一个ApiException.php文件:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class ApiException extends \Exception
{
   
    /**
     * $apiErrConst 是我们在自定义错误码的时候 已经定义好的常量
     * 只需要传过来就行了
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function __construct(array $apiErrConst, Throwable $previous = null)
    {

        parent::__construct($apiErrConst[1], $apiErrConst[0], $previous);

    }
}

修改原来的Handler.php文件中的render方法:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

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
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * 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)
    {
        
        // api接口主动抛出的异常
        if ($exception instanceof ApiException) {
            $code = $exception->getCode();
            $msg  = $exception->getMessage();
        }
        // 非API接口的异常在else中执行
        else{
            // 这里是laravel框架的异常处理方式
            // return parent::render($request, $exception);

            // 这里是我们自定义的异常处理方式
            $code = $exception->getCode();
            if (!$code || $code<0){
                $code = ApiErrDesc::UNKNOWN_ERROR[0];
            }
            $msg = $exception->getMessage()?: ApiErrDesc::UNKNOWN_ERROR[1];
        }
        $content = [
            'code' => $code,
            'msg'  => $msg,
            'data' => []
        ];
        // 异常返回
        return response()->json($content);
    }
}

  • 文件中的 return parent::render(request,exception); 是laravel的异常处理在开发的时后可以打开看到的就
    是这样
image.png
  • 如果不打开用自定义的话,下面这个显然不好调试嘛,不过上线可以注释掉
image.png

使用异常

这里以laravel中间件中token检测抛出异常为例
直接 throw new ApiException(ApiErrDesc::ERROR_PARAM);
其中 ApiErrDesc::ERROR_PARAM 为自定义的错误码文件

<?php

namespace App\Http\Middleware;

use App\Http\Response\ResponseJson; // 引入统一返回Trait
use App\Common\Err\ApiErrDesc; // 引入错误码管理文件
use App\Common\Auth\JwtAuth; // 引入JWT 生成和验证token类
use Closure;
use App\Exceptions\ApiException;

class JwtMiddleware
{
    use ResponseJson;
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    public function handle($request, Closure $next)
    {
        $result = $request->all();
        $token = $result['token'];
        if( $token ){
            // jwt验证类实例化
            $JwtAuth = JwtAuth::getinstance();
            $JwtAuth->setToken($token);
            
            // 验证token是否过期 被串改
            if(  $JwtAuth->verify() ){

                return $next($request);
            }else{
                throw new ApiException(ApiErrDesc::ERROR_LOGIN);
                // token 验证失败
                // return  $this->jsonErrorData(ApiErrDesc::ERROR_LOGIN[0], ApiErrDesc::ERROR_LOGIN[1]);
            }
        }else{
            throw new ApiException(ApiErrDesc::ERROR_PARAM);
            
            // token不存在
            // return  $this->jsonErrorData(ApiErrDesc::ERROR_PARAMS[0], ApiErrDesc::ERROR_PARAMS[1]);
        }
    }
    
}

相关文章

网友评论

      本文标题:Laravel 中自定义异常处理

      本文链接:https://www.haomeiwen.com/subject/cdysyctx.html