Reusing partially caught exceptions?

I have code that expects to accidentally receive a unique index violation when pasted into a remote database. It is impossible to avoid a violation, because I need a randomly generated, but human-readable value. Unfortunately, PDO just throws a generic PDOException when this happens, so I have a loop containing this nasty thing:

do {
        ...
   } catch (PDOException $e) {
       if ($e->getCode() === '23000') {
          continue; // have another go
      } else {
          throw new Exception("...", 1, $e); // reraise
      }
} while(there was an exception);

I think that catching errors will be better than searching and then pasting it because there will be little conflict at any time with a four-digit code and only a few hundred active codes.

SO questions such as best practices for catch and rethrow exceptions? and the exception of Rtrow php to a higher-level catch lock suggests that even in PHP this is bad practice. I will both catch the exception. I'm 99% sure I'm going to remodel, and I use exceptions to control the flow.

Is there a better way to do this in PHP, or is my only alternative to using a stored procedure in a database that returns an error code on failure, not an exception.

+4
source share
2 answers

, PHP , MySQL, . , , , .

PHP ( ) SQL ( ), , .

DECLARE CONTINUE HANDLER FOR 1062 -- duplicate key
    SET @dupe = 1;

SET @dupe = 0;
SET @attemptsLeft = 5;
REPEAT
    SET @user_code = randomString(4);
    INSERT INTO mytable(expires, user_code, users_id)VALUES(p_expires, @user_code, p_users_id);
    SET @attemptsLeft = @attemptsLeft - 1;
    -- if there a dupe we get the continue handler above
UNTIL @dupe = 0 OR @attemptsLeft <= 0 END REPEAT;
+3

, :

throw $e;
+2

Source: https://habr.com/ru/post/1546218/


All Articles