我正在做一个休息api项目。
我正在努力解决一个问题。当我收到令牌到期错误时,生成的代码将是这样的:
public function authenticate(Request $request){
$this->checkForToken($request);
try {
if (! $this->auth->parseToken()->authenticate()) {
throw new UnauthorizedHttpException('jwt-auth', 'User not found');
}
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
}
此代码写在此文件中:
供应商/ tymon / JWT-AUTH / SRC / HTTP /中间件/ BaseMiddleware.php
如何将其作为JSON类型返回?
答案 0 :(得分:3)
在 App \ Exceptions \ Handler 类'渲染方法中捕获该异常,并返回格式为json的响应:
// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...
public function render($request, Exception $exception)
{
// if your api client has the correct content-type this expectsJson()
// should work. if not you may use $request->is('/api/*') to match the url.
if($request->expectsJson())
{
if($exception instanceof UnauthorizedHttpException) {
return response()->json('Unauthorized', 403);
}
}
return parent::render($request, $e);
}