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;
} else {
throw new Exception("...", 1, $e);
}
} 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.
source
share