A real world Azure Function example that logs client errors in a Storage Table
Today I invested some time into getting deeper to the topic of Azure Functions. Together with the new microservices architecture, new ways of doing business logic arise. Azure Functions are small chunks of code that run in a “serverless” (you do not care about allocating new hardware resources, even when the requests to the function raise) environment and each of them is meant to do one specific job.
Apart from the great examples and templates with Functions that you can find inside the Azure Portal, I tried to think of some use cases that I would use an Azure Function for a web application and I came up with the following one:
Our application is a standard client-server web application. It is possible that the JavaScript code can run into exceptions or other non-expected errors and we want to store these exception in a data center.
On the JavaScript side we have to use the onerror global event and inside it do an Ajax POST-request to the Azure function by passing in the exception.
On the server side, we are going to write an Azure Function which receives the request, checks for its validity and then stores the exception along with the UserAgent of the client into a Storage Table. Storage Tables (NoSQL storages) are considered to be the best data storing option for log operations (store and forget operations), since they can store a massive amount of information and if needed they can return this data very fast.
Here it is important to mention, that we can use this function from multiple web applications, so that we log in a central database all the errors of our applications. This is why we also use the URL of the current application as property in the code.
The client code (I used TypeScript) is a simple page with a button which when is clicked throws an exception which is catched from onerror and then with jQuery we are doing an Ajax call to the Azure Function:
What’s important to mention is that you have to use a real domain name for the example to work and you will have to register this domain to the CORS table (see the following image) of the Azure Functions. If you try to test the example with a localhost URL it will not work because of the CORS policy of Azure.
Here is the HTML code:
Here is the code for the Azure Function:
and here is the configuration of the function:
That’s it. Drop me a line if you have any questions concerning Azure Functions or Azure Services in general.