Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json解码失败,小建议 #79

Open
Anthoney opened this issue Oct 13, 2024 · 0 comments
Open

json解码失败,小建议 #79

Anthoney opened this issue Oct 13, 2024 · 0 comments

Comments

@Anthoney
Copy link

Anthoney commented Oct 13, 2024

针对直接从response里直接解json。可以用try来容错。
譬如:

response = session.get(url).json()
    if response["code"] == 200:
        print("bark 推送成功!")
    else:
        print("bark 推送失败!")

如果可以改写成:

    try:
        response = session.get(url)
        # 检查响应状态码是否为200
        if response.status_code != 200:
            print(f"请求失败,状态码: {response.status_code}")
            return None
        else:
            print("bark 推送成功!") 
        # 检查响应内容是否为空
        if not response.text.strip():
            print("响应为空")
            return None
        # 尝试解析JSON
        try:
            json_data = response.json()
            return json_data
        except requests.exceptions.JSONDecodeError as e:
            print(f"JSON解码错误: {e}")
            return None
    except requests.RequestException as e:
        print(f"请求发生异常: {e}")
        return None 

会更好些吧。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant