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

Error raised from Flask app is logged as successful function execution #166

Merged
merged 7 commits into from
Mar 2, 2023
8 changes: 5 additions & 3 deletions azure/functions/_http_wsgi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from typing import Dict, List, Optional, Any
import logging
from io import BytesIO, StringIO
Expand Down Expand Up @@ -192,13 +191,16 @@ def _handle(self, req, context):
wsgi_request = WsgiRequest(req, context)
environ = wsgi_request.to_environ(self._wsgi_error_buffer)
wsgi_response = WsgiResponse.from_app(self._app, environ)
self._handle_errors()
self._handle_errors(wsgi_response)
return wsgi_response.to_func_response()

def _handle_errors(self):
def _handle_errors(self, wsgi_response):
if self._wsgi_error_buffer.tell() > 0:
self._wsgi_error_buffer.seek(0)
error_message = linesep.join(
self._wsgi_error_buffer.readline()
)
raise Exception(error_message)

if wsgi_response._status_code >= 500:
raise Exception(b''.join(wsgi_response._buffer))
16 changes: 16 additions & 0 deletions tests/test_http_wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import unittest
from io import StringIO, BytesIO

import pytest

import azure.functions as func
from azure.functions._abc import TraceContext, RetryContext
from azure.functions._http import HttpResponseHeaders
Expand Down Expand Up @@ -181,6 +183,20 @@ def main(req, context):
self.assertEqual(func_response.status_code, 200)
self.assertEqual(func_response.get_body(), b'sample string')

def test_middleware_handle_with_server_error_status_code(self):
"""Test if the middleware can be used by exposing the .handle method,
specifically when the middleware is used as
def main(req, context):
return WsgiMiddleware(app).handle(req, context)
"""
app = self._generate_wsgi_app(status="500 Internal Server Error",
response_body=b'internal server error')
func_request = self._generate_func_request()
with pytest.raises(Exception) as exec_info:
func_response = WsgiMiddleware(app).handle(func_request)
self.assertEqual(func_response.status_code, 500)
self.assertEqual(exec_info.value.args[0], b'internal server error')

def test_middleware_wrapper(self):
"""Test if the middleware can be used by exposing the .main property,
specifically when the middleware is used as
Expand Down