wesmiler 5 anni fa
parent
commit
787d42e2fd

+ 17 - 0
app/Exception/Handler/AppExceptionHandler.php

@@ -14,6 +14,7 @@ namespace App\Exception\Handler;
 use Hyperf\Contract\StdoutLoggerInterface;
 use Hyperf\ExceptionHandler\ExceptionHandler;
 use Hyperf\HttpMessage\Stream\SwooleStream;
+use Phper666\JWTAuth\Exception\TokenValidException;
 use Psr\Http\Message\ResponseInterface;
 use Throwable;
 
@@ -31,8 +32,24 @@ class AppExceptionHandler extends ExceptionHandler
 
     public function handle(Throwable $throwable, ResponseInterface $response)
     {
+        // 如果是授权异常
+        if ($throwable instanceof TokenValidException) {
+            // 格式化输出
+            $message = $throwable->getMessage();
+            $message = is_numeric($message)? __('api.'.$message) : $message;
+            $data = json_encode([
+                'code' => __('api.'.$throwable->getCode()),
+                'message' => $message
+            ], 256);
+
+            // 阻止异常冒泡
+            $this->stopPropagation();
+            return $response->withBody(new SwooleStream($data));
+        }
+
         $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
         $this->logger->error($throwable->getTraceAsString());
+
         return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
     }
 

+ 1 - 2
config/autoload/exceptions.php

@@ -13,8 +13,7 @@ return [
     'handler' => [
         'http' => [
             Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
-//            App\Exception\Handler\AppExceptionHandler::class,
-            App\Exception\Handler\TokenValidExceptionHandler::class,
+            App\Exception\Handler\AppExceptionHandler::class,
         ],
     ],
 ];