HandlesTelegramJobFailure.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Jobs\Concerns;
  3. use Illuminate\Support\Facades\Log;
  4. use RuntimeException;
  5. use Throwable;
  6. trait HandlesTelegramJobFailure
  7. {
  8. private function handleTelegramJobFailure(Throwable $exception, string $message, array $context = [], bool $shouldThrow = true): void
  9. {
  10. $safeMessage = $this->sanitizeTelegramError($exception->getMessage());
  11. $willRetry = $shouldThrow && $this->isRetryableTelegramJobError($safeMessage);
  12. $context = array_merge($context, [
  13. 'attempt' => method_exists($this, 'attempts') ? $this->attempts() : 1,
  14. 'error' => $safeMessage,
  15. 'exception' => get_class($exception),
  16. ]);
  17. Log::channel('issue')->warning($message, $context + [
  18. 'will_retry' => $willRetry,
  19. ]);
  20. if ($willRetry) {
  21. throw new RuntimeException($safeMessage);
  22. }
  23. }
  24. private function sanitizeTelegramError(string $message): string
  25. {
  26. return preg_replace('/bot\d+:[A-Za-z0-9_-]+/', 'bot[redacted]', $message);
  27. }
  28. private function isRetryableTelegramJobError(string $message): bool
  29. {
  30. return str_contains($message, 'Too Many Requests')
  31. || str_contains($message, 'retry after')
  32. || str_contains($message, 'cURL error 7')
  33. || str_contains($message, 'cURL error 28')
  34. || str_contains($message, 'Failed to connect')
  35. || str_contains($message, 'Connection timed out')
  36. || str_contains($message, 'Operation timed out');
  37. }
  38. }