Business central blog
Subscribe to blog and get news about new posts.

How to get Current Call Stack in AL?

Sometimes we need to know the current CallStack in the code, but what if we only have GetLastErrorCallStack and we don't have any error?

General

The discussion about adding this feature goes back as far as 2017, here's GitHub discussion and here's BC Idea.
It's actually a pretty standard function in other programming languages to get the current call stack. It is rather strange that the Business Central platform still does not have this feature. So what should we do if we need to know the current CallStack right now?
There is one way. It is codeunit 28 "Error Message Management", it contains GetCurrCallStack function, let's test its functionality.

var
  ErrorMessageMgt: Codeunit "Error Message Management";
  Customer: Record Customer;

Customer.FindFirst();
Customer.Name := 'This change will be commited!';
Customer.Modify(true);

Message(ErrorMessageMgt.GetCurrCallStack());

Message('Code is not blocked!');
Works wonders, is it some kind of magic and hidden system function? No, it's actually more simple than that, let's look at the implementation.

procedure GetCurrCallStack() CallStack: Text;
var
	Len: Integer;
	Pos: Integer;
	SubString: Text;
begin
	if ThrowError() then;
	CallStack := GetLastErrorCallStack();
	SubString := '"Error Message Management"(CodeUnit 28)';
	Len := StrLen(SubString);
	repeat
		Pos := StrPos(CallStack, SubString);
		CallStack := CopyStr(CallStack, Pos + Len);
	until Pos = 0;
	CallStack := CopyStr(CallStack, StrPos(CallStack, '\') + 1);
end;

[TryFunction]
local procedure ThrowError()
begin
	// Throw an error to get the call stack by GetLastErrorCallstack
	Error('');
end;
That is, we call an empty error in TryFunction to get GetLastErrorCallStack and remove the reference to the part of the CallStack where the empty error occurred.
While we don't have a method in AL Language yet, we can use this method from "Error Message Management".
March 7, 2024