Control execution and manage failures
Control statements determine which work runs and how often it runs. Error patterns determine whether an invalid condition stops the operation, rejects one input, or produces several findings for the user.
Match control flow to the business rule
Use if for one condition, case for a closed set of branches, and loops for repeated work. Prefer an enum and a case statement when each named domain value needs distinct behavior.
case ReviewPriority of
ReviewPriority::Low:
MinimumLeadTime := 30;
ReviewPriority::Normal:
MinimumLeadTime := 14;
ReviewPriority::High:
MinimumLeadTime := 7;
end;
Use exit for an intentional early return, such as a canceled upload. Avoid deeply nested branches by rejecting invalid preconditions before the main operation. In a loop, make the outcome of each iteration explicit so one row can't silently inherit state from the preceding row.
Choose an error pattern
Use Error when the current operation can't continue. Use a Label for messages that users see, and include the value that they can correct. Use TestField when a record field must be populated or equal a required value.
ErrorInfo separates a concise user message from troubleshooting details. It can also identify the record, field, or action associated with an error.
local procedure RaiseInvalidDate(RowNo: Integer; DateText: Text)
var
ImportError: ErrorInfo;
begin
ImportError.Title := InvalidRowTitleLbl;
ImportError.Message := StrSubstNo(InvalidDateErr, RowNo, DateText);
ImportError.DetailedMessage := 'The import expects an ISO date in YYYY-MM-DD format.';
Error(ImportError);
end;
Use error collection when users benefit from correcting several independent validation problems together. A procedure with [ErrorBehavior(ErrorBehavior::Collect)] can collect errors marked as collectible. The caller must inspect, present, or clear collected errors before the procedure ends.
Isolate recoverable validation with try methods
A procedure marked [TryFunction] becomes a try method when the caller consumes its Boolean return value. It returns false instead of propagating the error. The caller can inspect GetLastErrorText and continue with the next independent item.
if not TryPrepareRow(LineNo, ItemNoText, DateText, ItemNo, ReviewDate) then begin
LogRejectedRow(LineNo, GetLastErrorText);
exit;
end;
ApplyItemUpdate(ItemNo, ReviewDate);
Keep database writes outside the try method. Changes made by a try method aren't rolled back when its error is caught. Business Central online allows writes in try methods, while Business Central Server blocks them by default on-premises. Use the try method to parse and validate a row, then write only after it succeeds.
Calling a try method without consuming its return value makes its errors behave like normal errors. Make the intended failure boundary visible at the call site.
For more information, see AL control statements, Error handling overview, and Try methods.