Skip to main content
Question

Error handling uploading a file to Box 409

  • May 23, 2025
  • 1 reply
  • 93 views

Forum|alt.badge.img

I have this code which deliberately attempts to upload a file that already exists in the Box folder.

try:
    new_file = client.folder(8888888888888).upload('c.txt')
except:
    print('End')

 

How do I capture the "409" response from Box that tells me that the file already exists? For simplicity, I would like something like:

try:
    new_file = client.folder(8888888888888).upload('c.txt')
except 409:
    print('File already exist in Box, file will be updated' )

    updated_file = client.file(222222222222).update_contents('c.txt')

except 400:
    print('Some other error occurred' )

 

How do I get the identify the error and also retrieve the file ID from the error?

1 reply

Forum|alt.badge.img

Hi En,

In order to do this you need to capture the exception and look inside the error attributes, and inside the BoxAPIException (e.g. to get the conflicting file id)

Python example:

def upload_file(client: Client, folder_id: int, file_path: str) -> File:
  """ Upload a file to Box """
    try:
        file = client.folder(folder_id=folder_id).upload(file_path)
        print(f"Uploaded file: {file}")
        return file
    except BoxAPIException as err:
        if (
            err.status == 409
            and err.code == "item_name_in_use"
            and err.context_info["conflicts"]["type"] == "file"
        ):
            existing_file_id = err.context_info["conflicts"]["id"]
            print(
                f"File already exists, let's try updating it \nexisting_file_id: {existing_file_id}"
            )
            return update_file(client, existing_file_id, file_path)
      raise err

I would recommend you check more than just the generic 409 http error, there are plenty more details inside the BoxAPIException. For example there may be a name conflict with a folder name or a web-link object.

Check our this full example here.