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

Azure Function日志报错‘Unexpected end of request content’求助

Azure Function 无法捕获"Unexpected end of request content"错误

我有一个接收JSON格式HTTP请求的Azure Function,核心逻辑是:过滤传入JSON类型,识别到指定JSON后提取特定值生成新JSON,再通过POST请求发送至另一个Azure Function。但Azure日志中偶尔会出现Unexpected end of request content错误,我已添加多个Try-Except块尝试捕获该错误,但至今未成功。

函数代码

@app.route(route="webhooks/baas", auth_level=func.AuthLevel.ANONYMOUS)
def webhook_decoder_baas(req: func.HttpRequest) -> func.HttpResponse:
    # Imports and decodes the private_key used for sending extracted information
    private_key = os.environ["private_key_baas"]
    private_key_baas = base64.b64decode(private_key).decode("utf-8")
    
    # Declares the public_key for decoding the received webhook
    qi_public_key = '''-----BEGIN PUBLIC KEY-----
... :)
-----END PUBLIC KEY-----'''

    # Checks if the received webhook contains the correct parameters
    try:
        authorization = req.headers.get("AUTHORIZATION")
        body = req.get_json()

        # If AUTHORIZATION header is missing, returns an error.
        if not authorization:
            logging.error("AUTHORIZATION header not provided.")
            return HttpResponse("AUTHORIZATION header not provided.")
        
        # If no body content was sent, returns an error.
        if not body:
            logging.error("BODY content not provided.")
            return HttpResponse("BODY content not provided.")
        
        # Decodes the request using the PUBLIC_KEY.
        decoded_header = jwt.decode(token=authorization, key=qi_public_key)
        
        # Validates received data, returns error if any doesn't match.
        try:
            assert decoded_header.get("method") == "POST"
        except AssertionError as assertion_error:
            logging.error(f"Error in the sending method, a different method than POST was used.")
            return HttpResponse(f"Error in sending method, only POST is allowed.")
        
        try:
            assert decoded_header.get("payload_md5") == md5(json.dumps(body).encode()).hexdigest()
        except AssertionError as assertion_error:
            logging.error(f"Payload hash does not match the expected one.")
            return HttpResponse(f"Payload hash mismatch.")
        
        try:
            assert (datetime.utcnow() - timedelta(minutes=5)) < datetime.strptime(decoded_header.get("timestamp"), "%Y-%m-%dT%H:%M:%S.%fZ") < (datetime.utcnow() + timedelta(minutes=5))
        except AssertionError as assertion_error:
            logging.error(f"Error in sending timestamp, outside the 10-minute limit.")
            return HttpResponse(f"Timestamp outside allowed 10-minute window.")
                
    # Handles standard errors from the JWT library for errors in the received webhook token
    except jwt.JWTError as jwt_error:
        logging.error(f"Token error: {str(jwt_error)}")
        return HttpResponse(f"Token error: {str(jwt_error)}")
    
    # Handles standard Python errors
    except Exception as e:
        logging.error(f"Internal error while processing the webhook: {str(e)}")
        return HttpResponse(f"Internal error while processing webhook: {str(e)}")

    # Converts received data into a PYTHON object
    payload_string = json.dumps(body)
    objeto_payload = json.loads(payload_string)
        
    # Verifies if the received data meets the desired requirements
    if (
        objeto_payload.get("webhook_type") == "bank_slip.status_change" and 
        (objeto_payload.get("status") == "payment_notice" or objeto_payload.get("status") == "notary_office_payment_notice")
    ):
            
        # Extracts desired data from the received data
        bank_slip_key = objeto_payload.get("data", {}).get("bank_slip_key")
        paid_amount = objeto_payload.get("data", {}).get("paid_amount")

        # Creates a new PYTHON object with the extracted data
        payload_output = {
            key: objeto_payload[key] for key in ["status"]
        }

        payload_output['Paid amount'] = paid_amount
        payload_output['Query key of the title'] = bank_slip_key

        # URL to send the extracted data
        url = "https://nerowebhooks.azurewebsites.net/api/information/send"

        # Encrypts the data to be sent
        token = jwt.encode(payload_output, private_key_baas, algorithm='ES512')

        # Creates the sending header
        headers = {
            'SIGNATURE': token
        }

        # Sends the extracted information
        response = requests.post(url, headers=headers, json=payload_output)

        logging.info(f"Received webhook: {payload_output}")
        return HttpResponse("Webhook received successfully!", status_code=200)
    
    else:
        logging.info("Webhook received successfully, but it won't be handled at the moment!")
        return HttpResponse("Webhook received successfully, but no action taken at this time!")

预期接收的JSON格式

{
"key": "03c38d18-d12f-4b5f-841c-afab52fe33c5",
"data": {
"our_number": 142,
"paid_amount": 6676.38,
"payment_bank": 104,
"bank_slip_key": "03c38d18-d12f-4b5f-841c-afab52fe33c5",
"payment_method": 2,
"payment_origin": 3,
"paid_in": {
"name": "QI TECH",
"code_number": "329",
"ispb": "32402502"
},
"occurrence_type": "payment_notice",
"occurrence_feedback": "confirmed",
"occurrence_sequence": 0,
"requester_profile_code": "329-09-0001-0082162",
"registration_institution": "qi_scd",
"cnab_file_occurrence_order": 1,
"registration_institution_occurrence_date": "2021-04-19"
},
"status": "payment_notice",
"webhook_type": "bank_slip.status_change",
"event_datetime": "2021-04-19 20:04:06"
}

测试情况

测试阶段发送各类不同大小的JSON时,代码能有效捕获其他错误,但Unexpected end of request content错误始终无法被捕获。

内容的提问来源于stack exchange,提问作者Fabricio_Fortaleza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:42:05