How to set an Azure function that is internally calling a API to timeout in 7 seconds and provide graceful message to user instead of Internal Server Error?

Jaydeep Choudhury 1 Reputation point
2020-08-07T16:50:19.947+00:00

I have an Azure function that is calling a API which sometimes takes more than 30 seconds to respond. But in those cases, I want to kill the function and display message to user saying that they need to retry later. Setting function timeout displays "internal server error" screen. Is there any way to achieve this requirement?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,561 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Aakash Sharma 6 Reputation points
    2020-08-09T15:10:28.123+00:00

    It depends on what kind of function you are using and the architecture of your application. If it's an HTTP triggered function, you can simply handle the exception and return 408 from your Http function.

    0 comments No comments

  2. JayaC-MSFT 5,526 Reputation points
    2020-08-11T15:53:09.913+00:00

    @Jaydeep Choudhury The answer posted by Aakash should work. To add up to the answer, I am sharing the code snippet in C#. Here I am returning the in-built object result type with a custom error message. Let me know if this helps. The API which is called from the function has a sleep time of 7 seconds and httpclient times out in 5 seconds.

    HttpClient newClient = new HttpClient();  
                newClient.Timeout = TimeSpan.FromMilliseconds(5000);  
                string responseMessage = string.Empty;  
                int statuscode = 0;  
                try  
                {  
                    HttpRequestMessage newRequest = new HttpRequestMessage(HttpMethod.Post, string.Format("<API url>"));  
                    HttpResponseMessage response = await newClient.SendAsync(newRequest);  
                      
                    responseMessage = "Request has been processed successfully";  
      
                    return new OkObjectResult(responseMessage);  
                }  
                catch(Exception e)  
                {  
                    if (e.Message.ToString().ToUpper().Contains("CANCELED"))  
                        statuscode = StatusCodes.Status408RequestTimeout;  
                        responseMessage = "Status: " + statuscode + " - returned. Please retry after some time";  
                    return new BadRequestObjectResult(responseMessage);  
                }  
    

    Output looks like17023-image.png

    Please let me know if this helps.

    0 comments No comments