hyperf-chat/app/Exception/Handler/ValidateExceptionHandler.php

49 lines
1.3 KiB
PHP
Raw Normal View History

2020-11-04 11:57:16 +08:00
<?php
namespace App\Exception\Handler;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\ValidateException;
use Throwable;
/**
* 验证器异常处理类
* Class ValidateExceptionHandler
2021-04-20 16:30:57 +08:00
*
2020-11-04 11:57:16 +08:00
* @package App\Exception\Handler
*/
2020-11-04 16:47:17 +08:00
class ValidateExceptionHandler extends ExceptionHandler
2020-11-04 11:57:16 +08:00
{
2020-11-14 23:05:45 +08:00
/**
2021-04-20 16:30:57 +08:00
* @param Throwable $throwable
2020-11-14 23:05:45 +08:00
* @param ResponseInterface $response
* @return ResponseInterface
*/
2020-11-04 11:57:16 +08:00
public function handle(Throwable $throwable, ResponseInterface $response)
{
2021-05-24 11:31:36 +08:00
// 格式化输出
$data = json_encode([
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
], JSON_UNESCAPED_UNICODE);
2020-11-04 11:57:16 +08:00
2021-05-24 11:31:36 +08:00
// 阻止异常冒泡
$this->stopPropagation();
2020-11-04 11:57:16 +08:00
2021-05-24 11:31:36 +08:00
return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(200)->withBody(new SwooleStream($data));
2020-11-04 11:57:16 +08:00
}
/**
* 判断该异常处理器是否要对该异常进行处理
2020-11-14 23:05:45 +08:00
*
* @param Throwable $throwable
* @return bool
2020-11-04 11:57:16 +08:00
*/
public function isValid(Throwable $throwable): bool
{
2021-05-24 11:31:36 +08:00
return $throwable instanceof ValidateException;
2020-11-04 11:57:16 +08:00
}
}