Skip to main content
Question

Error Handling Python (ie. 409 error)

  • May 22, 2025
  • 1 reply
  • 23 views

Forum|alt.badge.img

Hi,

 

I've been working on a simple script to help upload files to box. 

 

I've noticed that when I try to upload a file that already exists I get a response back saying 

Message: Item with the same name already exists
Status: 409
Code: item_name_in_use

etc.

 

How do I properly handle these exceptions in Python?

 

For instance if I use boto3 to connect to s3 I can do:

 

try:
bucket.download_file(file_loc, local_storage_file_name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print(f"{s3_file_name} does not exist on s3.")
else:
raise

How do I do something similar for Box API? 

1 reply

Forum|alt.badge.img

Hi ,

 

Here's what you'll want to do:

  1. Listen for the 409 error with the item name in use description coming back whenever you're trying to upload a file (try / catch block) 
  2. When that error occurs, you can do a few things. You can instead call the update file endpoint to push a new file version up, or you can change the file name (e.g. filename(2).txt) and try the upload again.  

I don't have the code in Python, but I do in Node and Java, if that helps provide some guidance:

 

Node

client.files.uploadFile('0', 'tempdoc.txt', stream).then((err, metadata) => {
  console.log("file uploaded");
}).catch(function (err) {
  if (err.response && err.response.body && err.response.body.code === 'item_name_in_use') {
    console.log('duplicate file detected');
  }
});  

Java

String filePath = "/localdir/temp.txt";
String fileName = "current.txt";
String folderId = "0";

// Select Box folder
BoxFolder folder = new BoxFolder(client, folderId);
		
try {
    // Upload file
    FileInputStream stream = new FileInputStream(filePath);
    folder.uploadFile(stream, fileName);
    stream.close();
} catch (Exception e) {
    if (e.getMessage().contains("item_name_in_use")) {
        System.out.println("Duplicate file name detected");
    }
}