silent
silent

Reputation: 16128

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.

Upvotes: 3

Views: 9475

Answers (1)

Nkosi
Nkosi

Reputation: 247018

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
    };
}

//...

Upvotes: 5

Related Questions