The type or method ‘TryFunction” cannot be used for ‘Extension’ development

I am currently working on migrating extensions from version 1.0 to 2.0 – developed in the new Visual Studio Code development environment for Dynamics 365 Business. While I might be writing a blog about the entire process at a later point, I want to focus more on those “limitations” that are currently available.

One of them is the title of this post. You can use TryFunctions in Dynamics NAV or in Extension 1.0 to test for different conditions and provide errors when they are not true – and have the environment automatically catch the error and react on them in the calling code.

TryFunctions are not allowed in Extensions 2.0, unfortunately there is also not really a replacement yet. Ideally, I would like to see a true “try { } catch { }” introduced in Extensions 2.0, but this won’t happen until the database transaction handling is changed, which might not ever happen. You can read more about it on Vjeko’s blog here.

Now what do we do when we cannot use a TryFunction anymore? I guess there are two different options here and either one can be used in certain scenarios.

Boolean return value with an “error return parameter” in a function:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

codeunit70000000"Test for TryFunction"

{

// example for replacement of TryFunction

trigger OnRun();

begin

end;

procedure TryFunctionOption1(a:Boolean;varerrorMessage:Text):Boolean;

begin

ifnotathen begin

errorMessage:='A is not true';

exit(false);

end;

end;

}

Boolean return value with a global error message:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

codeunit70000000"Test for TryFunction"

{

// example for replacement of TryFunction

trigger OnRun();

begin

end;

var

globalErrorMessage:Text;

procedure TryFunctionOption2(a:Boolean):Boolean;

begin

ifnotathen begin

globalErrorMessage:='A is not true';

exit(false);

end;

end;

procedure GetError():Text;

begin

exit(globalErrorMessage);

end;

}

Both have some issues, especially when you are converting existing functionality. You don’t want to change the signature of functions, but if you do, it’s easier to spot where you missed updating your existing code. If you have additional options on how you would convert a TryFunction, let me know.