AppExceptionHandler.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace App\Exception\Handler;
  12. use App\Kernel\StdoutLogInterface;
  13. use Hyperf\Config\Annotation\Value;
  14. use Hyperf\Contract\StdoutLoggerInterface;
  15. use Hyperf\ExceptionHandler\ExceptionHandler;
  16. use Hyperf\HttpMessage\Stream\SwooleStream;
  17. use Psr\Http\Message\ResponseInterface;
  18. use Throwable;
  19. class AppExceptionHandler extends ExceptionHandler
  20. {
  21. /**
  22. * @var bool
  23. */
  24. #[Value("app_debug")]
  25. private $app_debug;
  26. public function __construct(protected StdoutLoggerInterface $logger, public StdoutLogInterface $stdoutLog)
  27. {
  28. }
  29. public function handle(Throwable $throwable, ResponseInterface $response)
  30. {
  31. $error = sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile());
  32. $error_string = $throwable->getTraceAsString();
  33. $this->logger->error($error);
  34. $this->logger->error($error_string);
  35. // 自定义日志通道
  36. if ($this->app_debug) {
  37. $this->stdoutLog->log->error($error);
  38. $this->stdoutLog->log->error($error_string);
  39. }
  40. // 根据debug输出异常
  41. $body = $this->app_debug ? "{$error}\n{$error_string}" : 'Internal Server Error.';
  42. return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream($body));
  43. }
  44. public function isValid(Throwable $throwable): bool
  45. {
  46. return true;
  47. }
  48. }