AppExceptionHandler.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Exception\Handler;
  4. use Hyperf\Contract\StdoutLoggerInterface;
  5. use Hyperf\ExceptionHandler\ExceptionHandler;
  6. use Hyperf\HttpMessage\Stream\SwooleStream;
  7. use Psr\Http\Message\ResponseInterface;
  8. use Throwable;
  9. /**
  10. * Create a new validation exception from a plain array of messages.
  11. *
  12. * @return static
  13. */
  14. class AppExceptionHandler extends ExceptionHandler
  15. {
  16. /**
  17. * Create a new validation exception from a plain array of messages.
  18. *
  19. * @return static
  20. */
  21. public function handle(Throwable $throwable, ResponseInterface $response)
  22. {
  23. // var_dump($throwable->getMessage());
  24. // 格式化输出
  25. $data = json_encode([
  26. 'code' => $throwable->getCode(),
  27. 'message' => $throwable->getMessage(),
  28. ], JSON_UNESCAPED_UNICODE);
  29. // 阻止异常冒泡
  30. $this->stopPropagation();
  31. return $response
  32. ->withAddedHeader('Content-Type', ' application/json; charset=UTF-8')
  33. ->withStatus(500)
  34. ->withBody(new SwooleStream($data));
  35. }
  36. public function isValid(Throwable $throwable): bool
  37. {
  38. return true;
  39. }
  40. }