简体   繁体   中英

KeyError exception's value is surrounded by single quotes

In order to provide better API error, I raise an exception KeyError if a specific key is missing in the API request.

user = {
    "id": 1234,
    "name": "John Doe"
}

try:
    user.pop("id") // for example purpose
    user_id = user["id"]
    print(user_id)
except KeyError as e:
    key_error_message = {
        "id": "Key 'id' is missing",
        "name": "Key 'name' is missing"
    }
    print(e) # 'id'
    print(type(e)) # <class 'KeyError'>
    print(str(e)) # 'id'
    print(type(str(e))) # <class 'str'>
    print(key_error_message.get(str(e))) # None
    print(key_error_message.get(str(e).replace("'", ""))) # Key 'id' is missing

I'm wondering why I have to remove single quote ' when I try to access KeyError's value? Is there a better way to do that?

I'm aware that there is certainly better way to do that with the use of .get() method of dict but this is the actual behavior in my code and I don't want to refactor it completly.

Use the args field to access the key name that caused the exception:

try:
    ....
except KeyError as e:
    missing_key = e.args[0]
    print(f"Key '{missing_key}' is missing")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM