PHP之JWT接口鉴权(二) 自定义错误异常

1.定义错误码,在App\Common\Err下创建ApiErrDesc.php

namespace App\Common\Err;

class ApiErrDesc{
    const SUCCESS = [0,'Success'];
    const UNKNOWN_ERR = [1,'未知错误'];
    const ERR_URL = [2,'访问的接口不存在'];
    const ERR_PARAMS = [100,'参数错误'];
    const ERR_PASSWORD = [1001,'密码错误'];
    const ERR_TOKEN = [1002,'登录过期'];
}
2.创建错误异常类,在App\Exceptions下创建ApiException.php(下面需要在中间件的Handle中调用)

namespace App\Exceptions;

use Throwable;
//异常类
class ApiException extends \RuntimeException{
    public function __construct(array $apiErrConst, Throwable $previous = null)
    {
        $code = $apiErrConst[0];
        $message = $apiErrConst[1];
        parent::__construct($message, $code, $previous);
    }
}
3.在App\Exceptions\Hander.php中的render方法写错误异常逻辑(核心)
public function render($request, Exception $exception)
    {
        //return parent::render($request, $exception);
        if($exception instanceof ApiException){  //如果$exception实现了ApiException的实例
            $code=$exception->getCode();
            $message=$exception->getMessage();
        }else{
            $code=$exception->getCode();
            if(!$code || $code<0){
                $code=ApiErrDesc::UNKNOWN_ERR[0]; //未知错误
            }
            $message=$exception->getMessage() ? $exception->getMessage() : ApiErrDesc::UNKNOWN_ERR[1]; //未知错误
        }
        return $this->jsonData($code,$message);
    }
    4.然后再App\Http\Middleware\JwtAuthMiddleware.php的handle方法编写抛出异常
    public function handle($request, Closure $next)
    {
        $token=$request->input('token');
        if(!empty($token)){
            $jwtauth=JwtAuth::getInstance();
            $jwtauth->setToken($token);

            if($jwtauth->validate() && $jwtauth->verify()){
                return $next($request);
            }else{
            	//自定义错误异常
                throw new ApiException(ApiErrDesc::ERR_TOKEN);
            }
        }else{
            //自定义错误异常
            throw new ApiException(ApiErrDesc::ERR_PARAMS);
        }
    }

在这里插入图片描述

你可能感兴趣的:(Laravel,功能)