I'm working with a php application, and there is a line that moves a file. I enclosed the method within a try...catch block so, if a error is thrown, can manage a rollback system. But the exception is never catched, so, renames throws any kind of exception? Do I need to try with another method?
Thanks
Code above:
try{
if(rename($archivo_salida, $ruta_archivos)){
//anything;
}
}catch (Exception $e)
//do something
}
"Normal" PHP functions don't throw exceptions.
Change your code to simulate an exception:
try{
if(rename($archivo_salida, $ruta_archivos)){
//anything;
} else {
throw new Exception('Can not rename file'.$archivo_salida);
}
}catch (Exception $e)
//do something
}
rename()
only ever returns true/false - there is no thrown exception.
It returns FALSE
on failure. See http://php.net/manual/en/function.rename.php
If you really need an exception to be thrown when the rename fails, you can do this:
if (rename($archivo_salida, $ruta_archivos)) {
// anything;
} else {
throw new Exception("Rename failed.");
}
Now, you can wrap this around a try {} catch {}
block where ever you are invoking this code.
You can also use the same approach as described in this answer: https://stackoverflow.com/a/43364340/563049
Create a custom exception class and use it's static constructor method with or
operator after rename()
.
Exception class:
class CustomException extends Exception {
static public function doThrow($message = "", $code = 0, Exception $previous = null) {
throw new Exception($message, $code, $previous);
}
}
Usage:
try {
rename($archivo_salida, $ruta_archivos) or CustomException::doThrow('Renaming failed.');
} catch (Exception $e){
//do something
}
Note
If you are using PHP 7 and higher - you can rename static method
doThrow()
to simplythrow()
, since in PHP 7 and higher it's allowed to use reserved keywords as method names.