| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- /**
- * Api异常处理.
- *
- * @author nj <nj@gmail.com>
- * @date 2019-11-03 15:07:19
- */
- declare(strict_types=1);
- namespace App\Exception\Handler;
- use App\Exception\ApiException;
- use Hyperf\ExceptionHandler\ExceptionHandler;
- use Psr\Http\Message\ResponseInterface;
- use Throwable;
- class ApiExceptionHanlder extends ExceptionHandler
- {
- public function handle(
- Throwable $throwable,
- ResponseInterface $response
- ) {
- // 判断被捕获到的异常是希望被捕获的异常.
- if ($throwable instanceof ApiException) {
- $message = $throwable->getMessage();
- $arrSrace = $throwable->getTrace();
- $strTrace = $throwable->getTraceAsString();
- $code = $throwable->getCode();
- // 格式化输出.
- $data = [
- 'code' => $code,
- 'array_trace' => $arrSrace,
- 'string_trace' => $strTrace,
- ];
- $data = [];
- if (env('APP_ENV', 'prod') == 'prod') {
- $data = [];
- }
- // 阻止异常冒泡.
- $this->stopPropagation();
- logger(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()), [], 'error');
- logger($throwable->getTraceAsString(), [], 'error');
- return json_fail($message, $code ?: 500, $data);
- }
- // 交给下一个异常处理器.
- return $response;
- }
- public function isValid(
- Throwable $throwable
- ): bool {
- return $throwable instanceof ApiException;
- }
- }
|