cloudfiles API: uncaught exception with get_container when container doesn't exist

799 Views Asked by At

I'm using the rackspace cloudfiles API to upload files on the fly and the first thing it needs to do is check whether the container exists and if not, create it.

So I write the following:

if($container = $conn->get_container('my_container')){
   echo 'yay';

} else {
   $container = $conn->create_container('my_container');
   $container->make_public();   
}                                           

But if the container doesn't exist get_container throws an exception and so I get a fatal error. What's the best way to do what I'm trying to do here?

2

There are 2 best solutions below

0
kwminnick On BEST ANSWER
try {
    $container = $conn->get_container('my_container');
    $obj_list = $container->list_objects();
    print_r($obj_list);
}
catch (Exception $e) {
    $container = $conn->create_container('my_container');
    //$container->make_public();
}
0
nitzer On

you could expect an explicit exception also:

try {
    $container = $conn->get_container('my_container');
    $obj_list = $container->list_objects();
    print_r($obj_list);
}
catch (NoSuchContainerException $e) {
    $container = $conn->create_container('my_container');
}

this will not fail if you have networking problems or something related.