You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
2.3 KiB
59 lines
2.3 KiB
<?php
|
|
|
|
namespace App\Exceptions;
|
|
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Throwable;
|
|
use Tymon\JWTAuth\Exceptions\JWTException;
|
|
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
|
|
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
|
|
class Handler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* The list of the inputs that are never flashed to the session on validation exceptions.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $dontFlash = [
|
|
'current_password',
|
|
'password',
|
|
'password_confirmation',
|
|
];
|
|
/**
|
|
* Register the exception handling callbacks for the application.
|
|
*/
|
|
public function register(): void
|
|
{
|
|
// 处理可报告的异常
|
|
$this->reportable(function (Throwable $e) {
|
|
// 可以在这里记录异常或执行其他操作
|
|
});
|
|
// 处理可渲染的异常
|
|
$this->renderable(function (\Exception $exception, Request $request) {
|
|
// 检查请求是否为 API 请求
|
|
if ($request->is('api*')) {
|
|
// 处理 JWT 相关的异常
|
|
if ($exception instanceof JWTException) {
|
|
// 映射 JWT 异常到用户友好的消息
|
|
$mapExceptions = [
|
|
TokenInvalidException::class => '无效的token',
|
|
TokenBlacklistedException::class => 'token 已被加入黑名单,请重新登录'
|
|
];
|
|
// 获取对应的错误消息
|
|
$msg = $mapExceptions[get_class($exception)] ?? $exception->getMessage();
|
|
return responseJsonAsUnAuthorized($msg); // 返回未授权的 JSON 响应
|
|
}
|
|
// 拦截表单验证错误抛出的异常
|
|
elseif ($exception instanceof ValidationException) {
|
|
return responseJsonAsBadRequest($exception->validator->errors()->first()); // 返回验证错误的 JSON 响应
|
|
}
|
|
// 处理其他服务器错误
|
|
return responseJsonAsServerError($exception->getMessage());
|
|
}
|
|
// 对于非 API 请求,返回服务器错误信息
|
|
return responseJsonAsServerError($exception->getMessage(), null);
|
|
});
|
|
}
|
|
}
|