API Management — Errors investigation
Hello, previously I talked about Azure API Management,how to automatically deploy it, how to configure it and how to use it.
Once your APIM is on production, If you don’t pay attention on how it was built, it will lead you to some fatal errors which can cause a production downtime. If you don’t have logs, the investigation becomes almost impossible. Here are some Tips to investigate API Management errors.
Enable a Logger
You should enable a logger such as Application Insights on your APIs. It gives you details on the exceptions.
- How to activate a logger :
Using Azure Powershell (For automation of course), you can use this script :
The script will create a logger, it will enable the diagnostic API for an API and it will attach it to a logger.
Unfortunatly, the module API Management on Powershell does not support the enabling of the Diagnostic and attaching it to a logger. So I created a rest API That will do it for you. You can paramize it and use it :)
Once is done, let’s send a request using APIM. We must see the logs in Application Insights.
The requests will appear on Application Insights.
You also can get the detail of a request
Let’s send another request
OUUUUPS ! ERROR 500 ! WHAT ?! HOW ?!
No worries, we can check the “exceptions” inside Application Insights which may help us to start the investigation or even solve the errors.
Well, the error is at “set-variable” level ! I can solve it easily since my Policy is simple :
I was trying to apply “contains” method on a header that does not exist. So APIM returns error 500.
In case if you have a complex policy, you should enable the “trace functionnality” !
Use the Trace functionnality
Api Management provides a functionnality to trace your request step by step. It requires the subscription key to be enabled.
This functionnality will block all the clients who are not providing the subscription key of using the API.
To bypass the problem,the idea is to clone your product and the API. Then enable the subscription key.
By adding the header “Ocp-Apim-Subscription-Key” and “Ocp-Apim-Trace” with true value, you may see request in detail and find the error.
If we try the same error as before
You will see exactly which section does not work and exactly what’s wrong !
On-Error Section
The “on-error” is not present in policies by default. It can be useful to handle some errors using the “proxyError” object which inside the “context.LastError”.
Then add these headers to the diagnostic API so you can see them in the Application Insights !
If we don’t add an on-error section, the client will receive errors with a status code of 500 which is not really signifient. Think to add a “return-response” with a signifient message.
Bella ciao,