I have a Carrierwave uploader that accepts multiple files and usage is set up in the typical way in the models.



mount_uploaders :attached_files, AttachedFileUploader



I’d like to make use of the content_type_allowlist functionality so I’ve overriden that in the uploader class.

def content_type_allowlist
    [
      'image/jpeg',
      'image/gif',
      'image/png',  . . .

This works. When a file with a content type on the list is uploaded, a CarrierWave::IntegrityError is thrown, which looks like it occurs in the cache function.



Where is the optimal way of catching this exception so I can return a message to the view. Out of the box I’m getting a 500 but I’d like to recover and return to the form. 

Are folks typically doing this inside the create and update methods in the controllers?

Ideally I’d like to do such a thing in a validator I have for other uploader rules




class AttachedFilesValidator < ActiveModel::Validator



But it seems like the exception occurs before that validation gets hit.

2

There are 2 best solutions below

1
engineersmnky On

It looks like all you have to do is tell the "uploader" to validate the integrity and this will be added as an error on the model, rather than raising an Error

mount_uploaders :attached_files, AttachedFileUploader, validate_integrity: true

That being said it seems like something else is going on here because that option is turned on by default:

  • Default Configuration Options Here

  • Uploader Options: Source

  • Currently your Error comes from Here

  • Validations to handle Errors can be found Here

0
Alex Dunae On

There is an option to ignore_integrity_errors that you can pass to mount. It will still add the errors to your ActiveRecord model but will no longer raise an exception.

Here's the code where Carrierwave decides whether to raise or not: https://github.com/carrierwaveuploader/carrierwave/blob/06579419cc8e4431095f96ea3fa47629181f56e1/lib/carrierwave/mounter.rb#L175-L186