Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper error handling for HTTP triggered Function?

What is the proper way to do error handling for HTTP triggered Azure Functions v2? Should - as recommend in this answer - all inner exceptions be caught and nothing ever be thrown?

I.e. always surround everything you do inside your function with try-catch, like this:

[FunctionName("DemoHttpFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
    try
    {
        await InnerDoSomething();
        return new NoContentResult();
    }
    catch(Exception ex)
    {
        log.LogError(ex, "Something went wrong");
        return new StatusCodeResult(500);
    }
}   

Drawbacks I see with that are

  1. No error message at all gets returned to the user. StatusCodeResult does not provide any overload to supply a message
  2. All executions of your function will show as successful, e.g. in the logging in Application Insights.
like image 539
silent Avatar asked Jun 29 '26 04:06

silent


1 Answers

No error message at all gets returned to the user. StatusCodeResult does not provide any overload to supply a message

You are in control of the code. You can easily use a different result that would include your desired information.

//...

catch(Exception ex)
{
    log.LogError(ex, "Something went wrong");
    var model = new { error = "User friendly something went wrong" };
    return new ObjectResult(model) {
        StatusCode = 500
    };
}

//...
like image 140
Nkosi Avatar answered Jun 30 '26 19:06

Nkosi