PHP rename() doesn't throws exception on error

此生再无相见时 提交于 2019-12-10 13:13:02

问题


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
}

回答1:


"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
}



回答2:


rename() only ever returns true/false - there is no thrown exception.

http://php.net/manual/en/function.rename.php




回答3:


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.




回答4:


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 simply throw(), since in PHP 7 and higher it's allowed to use reserved keywords as method names.



来源:https://stackoverflow.com/questions/10607373/php-rename-doesnt-throws-exception-on-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!