You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.5 KiB

  1. <?php
  2. namespace App\Exception\Handler;
  3. use App\Commons\Log;
  4. use App\Constants\v3\LogLabel;
  5. use App\Exception\ErrorCodeException;
  6. use Hyperf\Contract\StdoutLoggerInterface;
  7. use Hyperf\ExceptionHandler\ExceptionHandler;
  8. use Hyperf\HttpMessage\Stream\SwooleStream;
  9. use Psr\Http\Message\ResponseInterface;
  10. use Throwable;
  11. use Hyperf\Di\Annotation\Inject;
  12. class ErrorCodeExceptionHandler extends ExceptionHandler
  13. {
  14. /**
  15. * @Inject
  16. * @var Log
  17. */
  18. protected $log;
  19. /**
  20. * @var StdoutLoggerInterface
  21. */
  22. protected $logger;
  23. public function __construct(StdoutLoggerInterface $logger)
  24. {
  25. $this->logger = $logger;
  26. }
  27. public function handle(Throwable $throwable, ResponseInterface $response)
  28. {
  29. $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
  30. $this->logger->error($throwable->getTraceAsString());
  31. $this->stopPropagation();
  32. $content = [
  33. "status" => 'error',
  34. "code" => $throwable->getCode(),
  35. "result" => [],
  36. "message" => $throwable->getMessage()
  37. ];
  38. $this->log->event(LogLabel::ERROR_CODE_EXCEPTION, ['error_exception_msg' => $content['message']]);
  39. return $response->withHeader('Content-Type', 'application/json')
  40. ->withStatus(200)
  41. ->withBody(new SwooleStream(json_encode($content)));
  42. }
  43. public function isValid(Throwable $throwable): bool
  44. {
  45. return $throwable instanceof ErrorCodeException;
  46. }
  47. }