MG 2.2 XF\Db\DuplicateKeyException: MySQL query error [1062]: Duplicate entry

AndyB

Well-known member
About once or twice a day on a very active forum I see this:

XF\Db\DuplicateKeyException: MySQL query error [1062]: Duplicate entry

The stack trace shows:

src/addons/XFMG/Pub/Controller/Media.php(878): XFMG\Service\Media\Creator->save()

I suspect this is a race condition as it only occurs when a large number of files are being attached.

The code at 878 is:

1611496865223.png

Perhaps the best solution to this issue is to wrap the save in a try/catch.

PHP:
try
{
    $creator->save();
}
catch (\XF\Db\DuplicateKeyException $e) {}

Thank you.
 

Chris D

XenForo developer
Staff member
That's not really a catch-all solution. If there's a race condition it would be best to figure out why there is a race condition and figure out alternative approaches that may not be susceptible to such race conditions and, more importantly, if we were to catch the duplicate key exception, what actions do we want to take to recover from that.

In this case, catching the duplicate key exception and doing nothing as in your example is by no means an acceptable or expected behaviour because all it does is discard the media item that someone has tried to upload. And it does so silently without feeding that back to the user.

Imagine uploading 20 pictures to an album, but less than 20 are uploaded because the code has discarded them without warning or explanation.

This particular issue is not one that has been reported to us before and the full stack trace hasn't been provided so I strongly suspect something else is at play here. Therefore this requires more troubleshooting before we take any further action.
 
Top