42 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			42 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
| <?php
 | |
| 
 | |
| declare(strict_types=1);
 | |
| 
 | |
| namespace App\Exception\Handler;
 | |
| 
 | |
| use App\Constants\ErrorCode;
 | |
| use App\Helper\Result;
 | |
| use Hyperf\Context\Context;
 | |
| use Hyperf\ExceptionHandler\ExceptionHandler;
 | |
| use Hyperf\HttpMessage\Stream\SwooleStream;
 | |
| use Hyperf\JsonRpc\DataFormatter;
 | |
| use Psr\Http\Message\ResponseInterface;
 | |
| use Psr\Http\Message\ServerRequestInterface;
 | |
| use Throwable;
 | |
| 
 | |
| class AppRpcExceptionHandler extends ExceptionHandler
 | |
| {
 | |
|     public function handle(Throwable $throwable, ResponseInterface $response)
 | |
|     {
 | |
|         $message = $throwable->getMessage();
 | |
|         $error = explode('|', $message, 2);
 | |
|         $code = $error[1] ?? $throwable->getCode() ?: ErrorCode::COMMON_ERROR;
 | |
|         $data = Result::error($code, $error[0]);
 | |
| 
 | |
|         $dataFormatter = make(DataFormatter::class);
 | |
|         $request = Context::get(ServerRequestInterface::class);
 | |
|         $id = $request->getAttribute('request_id');
 | |
|         $result = $dataFormatter->formatResponse([$id, $data]);
 | |
|         $responseStr = json_encode($result, JSON_UNESCAPED_UNICODE);
 | |
| 
 | |
|         return $response->withHeader('Content-Type', 'application/json')->withBody(new SwooleStream($responseStr));
 | |
|     }
 | |
| 
 | |
|     /**
 | |
|      * 判断该异常处理器是否要对该异常进行处理
 | |
|      */
 | |
|     public function isValid(Throwable $throwable): bool
 | |
|     {
 | |
|         return true;
 | |
|     }
 | |
| } |