You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中IF分支触发KeyError致Else分支无法执行的问题

Fixing the KeyError: 'error' in Your Account Creation Code

Hey there, let's break down why you're hitting that frustrating KeyError: 'error' and get your code working as expected.

The Root of the Problem

Your current code tries to access response.json()['error'] immediately, before checking if that key even exists. When your account creation succeeds (the scenario where you want to enter the else branch), the response JSON almost certainly doesn't have an 'error' key—so trying to access it throws a KeyError right away, and your code never gets to the if/else check.

On top of that, you're calling response.json() twice, which is unnecessary and can lead to unexpected behavior if the response stream is consumed the first time.

Fixed Code Solutions

Let's rewrite this to safely handle both success and error cases. Here are two solid approaches:

Approach 1: Check for the 'error' key explicitly

First, store the parsed JSON response in a variable, then use the in keyword to verify the key exists before accessing it:

import sys

# Parse the response once and store it
response_data = response.json()

# Check if 'error' exists AND has a truthy value
if 'error' in response_data and response_data['error']:
    print("\nNotice =", response_data['error'])
else:
    sys.exit("Account Created Successfully")

Approach 2: Use dict.get() for safe key access

The get() method on dictionaries returns None (or a default value you specify) if the key doesn't exist, avoiding KeyErrors entirely:

import sys

response_data = response.json()

# Get the error message (returns None if 'error' doesn't exist)
error_message = response_data.get('error')

if error_message:
    print("\nNotice =", error_message)
else:
    sys.exit("Account Created Successfully")

Bonus Tip

If your successful response includes a specific key (like 'success' or 'status'), you could make the condition even clearer by checking for that instead—for example:

if response_data.get('success'):
    sys.exit("Account Created Successfully")
elif 'error' in response_data:
    print("\nNotice =", response_data['error'])

This makes your code more readable and aligned with the actual structure of the API responses.

内容的提问来源于stack exchange,提问作者Mohamed Abdel Fattah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:32:35