Handling exceptions inside NAV when using Web Services integration

In a forum post I’ve recently received a request on how to handle a scenario like the following: an external client application has to call a Microsoft Dynamics NAV object (codeunit) published as Web Service. The codeunit receives input data from the external application and then performs some operations on NAV (the business logic is managed by NAV itself).

If something wrong happens on the NAV transaction (error), NAV must be able to log the incoming request and the error that the request has caused, then returning a custom message to the client application.

As you know, if you publish a codeunit as web service from NAV and a client application calls a published method in this codeunit, if NAV throwns an error the transaction is immediately stopped and the client application receives an exception. NAV doesn’t handle Exceptions natively, so if C/AL throwns an error you can’t log it inside your C/AL code.

A way to handle this scenario is to use Try Functions: Try Functions in C/AL enable you to handle errors that occur in the application during code execution.

To give you a practical example, let’s define a codeunit with a public function for creating a Customer from an external application. This codeunit will be published as web service from NAV.

In the codeunit, we create a function called InsertCustomer (Local = No) that will be the method exposed to the external application.


Now we create a local function (private) called AddCustomer and here we set the property TryFunction to YES. In the AddCustomer function we have the code to handle the request (Customer creation):


The complete code is as follows:


The public method InsertCustomer calls the TryFunction AddCustomer.

If no errors occours, we can return to the external client (or log inside NAV) the success result of the transaction.

If an error occours on NAV, with the TryFunction we can catch the error, log it in NAV (with system variables like GETLASTERRORCODE, GETLASTERRORTEXT, GETLASTERROROBJECT, GETLASTERRORCALLSTACK) and return a custom error message to the external client.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s