Magento – How to handle exception in magento 2

exceptionimage-uploadmagento2

I have prepared one module in which I have used Image upload button. And My button is working fine unless I am not entering any "Disallowed file type". When I enter any disallowed file type it gives me exception.

I have written the below function to upload file of my required file-type and to handle exception. I have also prepared required block and model file for image upload. I have followed this post

public function uploadFileAndGetName($input, $destinationFolder, $data)
{
    try {
        if (isset($data[$input]['delete'])) {
            return '';
        } else {
            $uploader = $this->uploaderFactory->create(['fileId' => $input]);
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            $result = $uploader->save($destinationFolder);
            return $result['file'];
        }
    } catch (\Exception $e) {
        if ($e->getCode() != \Magento\Framework\File\Uploader::TMP_NAME_EMPTY) {
            throw new FrameworkException($e->getMessage());
        } else {
            if (isset($data[$input]['value'])) {
                return $data[$input]['value'];
            }
        }
    }
    return '';
}

When I enter any disallowed file-type, it gives me blank page and gives error "Disallowed file type".

If anyone faced this issue, please help me.

Best Answer

In my case it was due to the Exception class in the throw block. I'm using magento 2.17, the Uploader class throws Exception class. Please check framework/file/Uploader.php:: _validateFile(). Makesure the Exception class in the Uploader throw block and your Exception reference in your code is identical. My case it is worked: framework/file/Uploader.php:

  protected function _validateFile()
{
    if ($this->_fileExists === false) {
        return;
    }

    //is file extension allowed
    if (!$this->checkAllowedExtension($this->getFileExtension())) {

        throw new \Exception('Disallowed file type.');
    }
    //run validate callbacks
    foreach ($this->_validateCallbacks as $params) {
        if (is_object($params['object'])
            && method_exists($params['object'], $params['method'])
            && is_callable([$params['object'], $params['method']])
        ) {
            $params['object']->{$params['method']}($this->_file['tmp_name']);
        }
    }
}

And in my code it was like:

try {
                $this->_fileUploaderFactory = $this->_objectManager->get('Magento\MediaStorage\Model\File\UploaderFactory');
                $uploader = $this->_fileUploaderFactory->create(['fileId' => 'banner']);

                $uploader->setAllowedExtensions(['jpg', 'jpeg','png']);

                $uploader->setAllowRenameFiles(false);
                $uploader->setFilesDispersion(false);
                $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                    ->getDirectoryRead(DirectoryList::MEDIA);
                $path           = $mediaDirectory->getAbsolutePath('bannerslider/images/');


                $result = $uploader->save($path);


                $data['banner'] = isset($result['file']) ? $result['file'] : null;
            } catch (\Exception $e) {

                $data['banner'] = $_FILES['banner']['name'];
                $this->messageManager->addError($e->getMessage());

                $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

                // Your code

                $resultRedirect->setUrl($this->_redirect->getRefererUrl());
                return $resultRedirect;

            }