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.

  1. Boolean return value with an “error return parameter” in a function:
    codeunit 70000000 "Test for TryFunction"
    {
      // example for replacement of TryFunction
    
      trigger OnRun();
      begin
      end;
    
      procedure TryFunctionOption1(a :Boolean;var errorMessage : Text) : Boolean;
      begin
          if not a then begin
            errorMessage := 'A is not true';
            exit(false);
          end;
      end;
    }

     
  2. Boolean return value with a global error message:
    codeunit 70000000 "Test for TryFunction"
    {
      // example for replacement of TryFunction
    
      trigger OnRun();
      begin
      end;
    
      var
        globalErrorMessage : Text;
    
      procedure TryFunctionOption2(a :Boolean) : Boolean;
      begin
          if not a then 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.