Handler.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\miniapi\exception;
  4. use app\miniapi\http\ApiResponse;
  5. use Webman\Http\Request;
  6. use Webman\Http\Response;
  7. /** Only mini API failures use the new contract; existing root and plugin behavior is preserved. */
  8. final class Handler extends \support\exception\Handler
  9. {
  10. public function report(\Throwable $exception)
  11. {
  12. $request = \request();
  13. if (!$request || !ApiResponse::owns($request)) {
  14. if (!$exception instanceof ApiException) {
  15. parent::report($exception);
  16. }
  17. return;
  18. }
  19. if (!$exception instanceof ApiException) {
  20. $this->logger->error('mini_api.error', [
  21. 'request_id' => ApiResponse::requestId($request),
  22. 'exception_type' => get_class($exception),
  23. 'file' => $exception->getFile(),
  24. 'line' => $exception->getLine(),
  25. 'trace' => array_map(static fn ($frame) => array_intersect_key($frame, array_flip([
  26. 'file',
  27. 'line',
  28. 'class',
  29. 'function',
  30. ])), array_slice($exception->getTrace(), 0, 15)),
  31. ]);
  32. }
  33. }
  34. public function render(Request $request, \Throwable $exception): Response
  35. {
  36. if (!ApiResponse::owns($request)) {
  37. return parent::render($request, $exception);
  38. }
  39. $error = $exception instanceof ApiException ? $exception : ($exception instanceof \plugin\saiadmin\exception\ApiException
  40. ? new ApiException(40902, $exception->getMessage(), 409) : new ApiException(50001, '服务暂时不可用', 500));
  41. return ApiResponse::error($request, $error);
  42. }
  43. }