I'm trying to find out whether a blob exists or not. When the blob does not exist, my try-catch with Azure's ServiceException isn't being caught at all. I tried following the steps from here.
public function checkBlobExists($path) {
$container = config('azure.storage.container');
$blobClient = ServicesBuilder::getInstance()->createBlobService(config('azure.storage.connection_string'));
try {
$blob = $blobClient->getBlob($container, $path);
return true;
} catch (ServiceException $e) {
return false;
}
return false;
}
This is some of the error stack:
ServiceException in ServiceRestProxy.php line 491:
Fail:
Code: 404
Value: The specified blob does not exist.
details (if any): .
in ServiceRestProxy.php line 491
at ServiceRestProxy::throwIfError(object(Response), array('200', '206')) in ServiceRestProxy.php line 409
at ServiceRestProxy->MicrosoftAzure\Storage\Common\Internal\{closure}(object(ClientException)) in Promise.php line 203
You may not be using the fully qualified exception class name. Try:
//...
} catch (\MicrosoftAzure\Storage\Common\Exceptions\ServiceException $e) {
//...
}
Related
Hi everyone! In my Laravel application I have a upload function for an Excel file. I got this code from the web and adjusted it to my application. The problem is, it doesn't catch a fatal error exception which is produced when the user submits a file, but hasn't selected a file. I don't understand why it is not being caught. I will add a part of my controller.
public function upload() {
$file = array('thefile' => Input::file('thefile'));
$rules = array('excel' => 'excel');
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
return Redirect::to('UploadExcelFile')->withInput()->withErrors($validator);
}
else {
try{
// FatalErrorException happens in this line!
if (Input::file('thefile')->isValid()) {
$destinationPath = 'uploads';
$fileName = Input::file('thefile')->getClientOriginalName();
Input::file('thefile')->move($destinationPath, $fileName);
Session::flash('success', 'Upload successfully');
$fileNameJSON = exec("python /path/to/script/ExcelToJSON3.py $fileName"); // This returns a full path name of the JSON file that is made...
if ($fileNameJSON == null){
return Redirect::to('/dashboard/input');
}
else {
// Getting the ID from the file that is uploaded
try {
$jsonDecode = json_decode(file_get_contents($fileNameJSON));
} catch (ErrorException $e){
return Redirect::to('/errorpage')->with(array('status'=> 'ErrorException'));
}
A lot of code for handling the data entered....
}catch (FatalErrorException $e){
return Redirect::to('/errorpage')->with(array('status'=> 'FatalErrorException'));
}
}
return true;
}
The error that is given:
FatalErrorException in UploadExcelFileController.php line 35:
Call to a member function isValid() on a non-object
So, I don't understand why this code doesn't handle the error exception and how I could fix this!
Unless you've imported the namespace that FatalErrorException is declared in with "use" you will need to scope the exception, like this:
catch (\Symfony\Component\Debug\Exception\FatalErrorException $e) {
Otherwise you're using whatever namespace your class is in and trying to catch an exception that is declared in that namespace. It looks like your ErrorException is similarly set up.
I'm not sure that the namespace above is the one your class is deriving from, I'm just guessing it is because you're using Laravel.
I am trying to catch the exception while uploading file in zend framework 1.
I denied permission to the folder and then ran the following code to catch the exception but it is not working.
public function uploadImage($postedFile,$destination) {
try {
$imageName = $this->getFileName($postedFile); //$postedFile is same as $_FILES
$upload = new Zend_File_Transfer();
foreach ($upload->getFileInfo($imageName) as $info) {
if ($info['name'] != '') {
$ext = pathinfo($info['name'], PATHINFO_EXTENSION);
$newName = md5(rand(1, 100).date('ymdhis') . $info['name']) . '.' . $ext;
$upload->addFilter('Rename', $destination."/".$newName);
if (!$upload->receive($info['name'])) {
return FALSE;
}
}
break;
}
return $newName;
} catch (Zend_File_Transfer_Exception $e) {
throw new Exception('I want to catch this');
}
}
error:
Warning:
move_uploaded_file(/var/www/html/glistonapp/application/../public/images/app_user_profile_picture/80d55d25c52ef4d74079cfa903288b77.png):
failed to open stream: Permission denied in /var/www/html/glistonapp/library/Zend/File/Transfer/Adapter/Http.php on line 189
Warning: move_uploaded_file(): Unable to move '/tmp/phpOtOLVv' to '/var/www/html/glistonapp/application/../public/images/app_user_profile_picture/80d55d25c52ef4d74079cfa903288b77.png' in /var/www/html/glistonapp/library/Zend/File/Transfer/Adapter/Http.php on line 189
It doesn't appear that the methods you are calling on the Zend_File_Transfer object will throw an exception.
Without a thrown exception, you won't be able to "catch" anything in your try block. Instead, you should check the return values of the functions you are calling to determine if there was a problem.
See the API reference which will tell you which methods throw exceptions:
http://framework.zend.com/apidoc/1.12/classes/Zend_File_Transfer_Adapter_Abstract.html
Your error message is not an exception, therefore it won't be caught by the try/catch block.
You should set the appropriate permissions on the destination directory for that error message.
I have code like this:
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = file_get_contents($nbg_xml_url);
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}`
and problem is that, when file_get_contents can not read url (may be site not responding or something like this..) my code writes error: failed to open stream: HTTP request failed! and execution goes direct to finally block bypass catch block without entering in it..
any ideas?
You can set an empty error handler to prevent the warning and afterward throw a custom exception in case of failure. In this case I would write a custom file_get_content like so:
function get_file_contents($url) {
$xml_content = file_get_contents($url);
if(!$xml_content) {
throw new Exception('file_get_contents failed');
}
return $xml_content;
}
and would use it in your block:
set_error_handler(function() { /* ignore errors */ });
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = get_file_contents($nbg_xml_url); //<----------
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}
Then remember to restore the error handler calling:
restore_error_handler();
Note that when using your own error handler it will bypass the
error_reporting
setting and all errors included notices, warnings, etc., will be passed to it.
$xml_content = file_get_contents($nbg_xml_url);
The function file_get_contents does not throw an exception. Thus an exception will not be thrown if as you say the file is not found.
From the docs:
An E_WARNING level error is generated if filename cannot be found...
This function returns the read data or FALSE on failure. So you could check if $xml_content is FALSE ($xml_content === false) and proceed accordingly.
This is a php code for catching any error or exception.
Throwable is the base interface for any object that can be thrown via a throw statement, including Error and Exception.
This will catch fatal errors too. Without throwable it will not catch fatal errors.
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}
I'm trying to catch a Laravel exception inside my library.
namespace Marsvin\Output\JoomlaZoo;
class Compiler
{
protected function compileItem($itemId, $item)
{
$boom = explode('_', $itemId);
$boom[0][0] = strtoupper($boom[0][0]);
$className = __NAMESPACE__."\\Compiler\\".$boom[0];
try {
$class = new $className(); // <-- This is line 38
} catch(\Symfony\Component\Debug\Exception\FatalErrorException $e) {
throw new \Exception('I\'m not being thrown!');
}
}
}
This it the exception I'm getting:
file: "C:\MAMP\htdocs\name\app\libraries\WebName\Output\JoomlaZoo\Compiler.php"
line: 38
message: "Class 'Marsvin\Output\JoomlaZoo\Compiler\Deas' not found"
type: "Symfony\Component\Debug\Exception\FatalErrorException"
The name of the class is voluntarily wrong.
Edit 1:
I noticed that if I throw an exception inside the try statement I can catch the exception:
try {
throw new \Exception('I\'d like to be thrown!');
} catch(\Exception $e) {
throw new \Exception('I\'m overriding the previous exception!'); // This is being thrown
}
The problem is that you're trying to catch a FatalErrorException in your class, but Laravel won't let a fatal error get back there; it terminates immediately. If your were trying to catch a different kind of exception, your code would work just fine.
You can catch and handle fatal errors with an App::fatal method in app/start/global.php, but that won't help you deal with the exception from within your library, or to handle it with any specificity. A better option would be to trigger a "catchable" exception (something from Illuminate, for instance), or to throw a custom one based on the condition that you are trying to check.
In your case, if your goal is to deal with undefined classes, here's what I would suggest:
try {
$className = 'BadClass';
if (!class_exists($className)) {
throw new \Exception('The class '.$className.' does not exist.');
}
// everything was A-OK...
$class = new $className();
} catch( Exception $e) {
// handle the error, and/or throw different exception
throw new \Exception($e->getMessage());
}
I use imagick to create thumbnails of PDF files, but in some cases imagic returns a Fatal Error.
I am looking for a way to know when the fatal error occurs.
Something like this:
function MakeThumb($source) {
if($im = new imagick($source)) {
//Generate thumbnail
return($thumb);
} else {
return 'no_thumb.png'; // then we will not tray again later.
}
}
You could do something like this
function MakeThumb($source) {
try {
//throw exception if can't create file
if(!$im = new imagick($source) {
throw new Exception('Count not create thumb');
}
//ok if got here
return($thumb);
} catch (Exception $e) {
return 'no_thumb.png';
}
}
I haven't tested it,but by using Try Catch, you can make it work
http://php.net/manual/en/language.exceptions.php