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.
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?
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?
2 answers
Sort by: Most helpful
-
-
JayaC-MSFT 5,531 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 like
Please let me know if this helps.