Hooch
Hooch

Reputation: 29673

Azure Function should log or throw exception on error?

I have Azure Function (Http trigger) that can fail. I also have Application Insights configured for it.

In case of error (Which is better):

  1. Catch exception, wrap with more info and rethrow it. (Sends 500 response) OR
  2. Catch exception, log it, wrap it, rethrow it to caller. (Sends 500 response) OR
  3. Catch exception, log it (Don't throw it), Manual send 500 response.

Application Insight is able log exceptions. I don't really see point in logging error and throwing exception at the same time.

What are the guidelines? What is good practise?

Upvotes: 16

Views: 10195

Answers (2)

sandejd1
sandejd1

Reputation: 55

Guidelines for error handling in Azure Functions are documented here. Specifically

The top-most level of any function code should include a try/catch block. In the catch block, you can capture and log errors. ... Depending on your specific retry strategy, you might also raise a new exception to run the function again.

I agree that it seems redundant to log the error and throw another. The likely reason for a new exception is to prevent accidentally leaking details to your callers.

Upvotes: 1

ben cohen
ben cohen

Reputation: 21

From my experience which is building an HTTP triggered azure function with Python, I noticed that: When handling exceptions and then manually return something to the client you do have control over the function returned value but the framework marks the function's job as 'Succeeded', which then makes it more difficult to be tracked & monitored in the Application Insights.

For your question, I ended up with a catch clause that mixes 1 & 3 i.e a hybrid approach where I try to identify the origin of the exception, then for exceptions from my code I'm wrapping it and return 500, and for other exceptions that originated from code that I'm using I re-throw them and let the azure function framework return a 500 and to mark the function's job as 'Failed'.

Upvotes: 2

Related Questions