ApiExceptionHanlder.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Api异常处理.
  4. *
  5. * @author nj <nj@gmail.com>
  6. * @date 2019-11-03 15:07:19
  7. */
  8. declare(strict_types=1);
  9. namespace App\Exception\Handler;
  10. use App\Exception\ApiException;
  11. use Hyperf\ExceptionHandler\ExceptionHandler;
  12. use Psr\Http\Message\ResponseInterface;
  13. use Throwable;
  14. class ApiExceptionHanlder extends ExceptionHandler
  15. {
  16. public function handle(
  17. Throwable $throwable,
  18. ResponseInterface $response
  19. ) {
  20. // 判断被捕获到的异常是希望被捕获的异常.
  21. if ($throwable instanceof ApiException) {
  22. $message = $throwable->getMessage();
  23. $arrSrace = $throwable->getTrace();
  24. $strTrace = $throwable->getTraceAsString();
  25. $code = $throwable->getCode();
  26. // 格式化输出.
  27. $data = [
  28. 'code' => $code,
  29. 'array_trace' => $arrSrace,
  30. 'string_trace' => $strTrace,
  31. ];
  32. $data = [];
  33. if (env('APP_ENV', 'prod') == 'prod') {
  34. $data = [];
  35. }
  36. // 阻止异常冒泡.
  37. $this->stopPropagation();
  38. logger(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()), [], 'error');
  39. logger($throwable->getTraceAsString(), [], 'error');
  40. return json_fail($message, $code ?: 500, $data);
  41. }
  42. // 交给下一个异常处理器.
  43. return $response;
  44. }
  45. public function isValid(
  46. Throwable $throwable
  47. ): bool {
  48. return $throwable instanceof ApiException;
  49. }
  50. }