AppExceptionHandler.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 Hyperf\Contract\StdoutLoggerInterface;
  13. use Hyperf\ExceptionHandler\ExceptionHandler;
  14. use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
  15. use Hyperf\HttpMessage\Stream\SwooleStream;
  16. use Psr\Http\Message\ResponseInterface;
  17. use Throwable;
  18. use Hyperf\Utils\Str;
  19. class AppExceptionHandler extends ExceptionHandler
  20. {
  21. /**
  22. * @var StdoutLoggerInterface
  23. */
  24. protected $logger;
  25. /**
  26. * @var FormatterInterface
  27. */
  28. protected $formatter;
  29. public function __construct(StdoutLoggerInterface $logger, FormatterInterface $formatter)
  30. {
  31. $this->logger = $logger;
  32. $this->formatter = $formatter;
  33. }
  34. public function handle(Throwable $throwable, ResponseInterface $response)
  35. {
  36. $message = $throwable->getMessage();
  37. $arrSrace = $throwable->getTrace();
  38. $strTrace = $throwable->getTraceAsString();
  39. $code = $throwable->getCode();
  40. $this->logger->error(sprintf('%s[%s] in %s', $message, $throwable->getLine(), $throwable->getFile()));
  41. $this->logger->error($strTrace);
  42. $clientRequest = request();
  43. $headerContentType = $clientRequest->header('content-type');
  44. if (!empty($headerContentType) && Str::contains($headerContentType, ['/json', '+json'])) {
  45. // 是Json请求.
  46. // 格式化输出.
  47. $data = [
  48. 'code' => $code,
  49. 'array_trace' => $arrSrace,
  50. 'string_trace' => $strTrace,
  51. ];
  52. if (env('APP_ENV', 'prod') == 'prod') {
  53. $message = '内部错误';
  54. $data = [];
  55. }
  56. return json_fail($message, 500, $data);
  57. } else {
  58. return $response->withStatus(500)->withBody(new SwooleStream('内部错误.'));
  59. }
  60. }
  61. public function isValid(Throwable $throwable): bool
  62. {
  63. return true;
  64. }
  65. }