Using Built-in Functions and Managing Errors
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 9 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Using Built-in Functions and Managing Errors in AL
Introduction: Why Mastering AL Functions and Error Handling Matters
When you develop extensions for Microsoft Dynamics 365 Business Central using the AL (Application Language) programming language, you are essentially building logic that interacts with a massive, complex database structure. AL is a domain-specific language designed for business processes, and as such, it comes equipped with a rich library of built-in functions that handle everything from date calculations and string manipulation to complex data filtering and mathematical operations. Understanding how to utilize these functions effectively is the difference between writing clean, maintainable code and writing code that is prone to performance bottlenecks and bugs.
Beyond simply executing tasks, the most critical aspect of professional AL development is how your code handles the unexpected. Business Central is a multi-tenant, highly active environment where data integrity is paramount. If your code fails silently or crashes during a transaction, it can lead to corrupted financial data or frustrated users who lose their progress. Mastering error handling—knowing when to throw an error, how to catch exceptions, and how to provide meaningful feedback to the end-user—is not just an optional skill; it is a fundamental requirement for any developer working within the Business Central ecosystem. This lesson will guide you through the standard library of functions and the patterns required to build resilient, error-aware applications.
Not read yet
Part 1: Leveraging AL Built-in Functions
AL provides a wide array of built-in functions categorized by their purpose. Whether you are working with text, dates, numbers, or records, there is likely a pre-built function that can save you from writing custom logic. Using these functions is preferred over manual implementations because they are optimized for the Business Central platform and are maintained by Microsoft.
String and Text Manipulation
Text processing is a daily task in ERP development, whether you are formatting customer names, validating email addresses, or concatenating strings for reports.
- StrLen(String): Returns the length of a string.
- CopyStr(String, Position, [Length]): Extracts a substring. This is safer than array indexing because it handles out-of-bounds requests gracefully.
- StrPos(String, Substring): Finds the starting position of a substring within a string.
- Upper/Lower Case: Simple methods to normalize user input for comparison purposes.
Callout: The Power of
Format()TheFormat()function is perhaps the most versatile tool in your AL toolkit. It converts any data type—whether it is a Record, a Date, a Decimal, or an Option—into a human-readable string. Use it when you need to log messages, display information in a dialog box, or generate output for an external integration. However, be mindful that the format depends on the user's regional settings, so avoid relying onFormat()for data that must be parsed by a machine across different locales.
Date and Time Functions
Business Central relies heavily on dates for financial periods, due dates, and scheduling. AL provides functions that respect the calendar and fiscal year definitions.
- Today: Returns the current system date.
- WorkDate: Returns the current "Work Date" set by the user in the client, which is crucial for accounting entries that need to be posted on a date other than the system clock.
- CalcDate(DateExpression, [Date]): This is the most powerful date function. It allows for complex logic like
'+1M+CM'(one month from now, plus the end of the month). - Date2DMY(Date, Part): Extracts the Day, Month, or Year from a date variable.
Mathematical Functions
While AL is not a scientific computing language, it handles financial math with high precision.
- Abs(Number): Returns the absolute value.
- Round(Number, [Precision], [Direction]): Essential for currency handling. You can specify whether to round up, down, or to the nearest value, which is vital for compliance with local tax laws.
- Power(Base, Exponent): Used for interest calculations or statistical projections.
Not read yet
Part 2: Practical Implementation of Functions
To see these in action, let's look at a scenario where we need to validate a "Product Code" format and calculate a shipping deadline.
procedure ValidateAndCalculate(ProductCode: Text; OrderDate: Date)
var
FormattedCode: Text;
ShippingDate: Date;
begin
// Validate that the code is long enough
if StrLen(ProductCode) < 5 then
Error('The product code must be at least 5 characters long.');
// Extract a category and normalize it
FormattedCode := UpperCase(CopyStr(ProductCode, 1, 3));
// Calculate shipping: 3 days from the order date, but skip weekends
// Note: CalcDate handles business days if configured,
// but here we use a simple approach for demonstration
ShippingDate := CalcDate('<+3D>', OrderDate);
Message('Category: %1, Shipping Date: %2', FormattedCode, ShippingDate);
end;
Tip: Avoiding Manual Loops Whenever you find yourself writing a
repeat...untilloop to manipulate a string or a list, pause and check theSystemlibrary in the AL documentation. Often, there is a built-in function likeSelectStr,StrSubstNo, or a collection method that performs the same action more efficiently and with less risk of infinite loops.
Not read yet
Part 3: Mastering Error Handling in AL
Error handling in Business Central is unique because the platform operates on a "transactional" basis. When an error is thrown, the entire transaction is rolled back. This ensures that the database never ends up in a partially updated, inconsistent state.
Using the Error Function
The Error function is the primary way to stop execution. When you call Error('Message'), the platform stops, rolls back all changes made in the current transaction, and displays the message to the user.
- When to use: Use
Errorwhen the user has provided invalid data that makes it impossible to proceed, or when a business rule has been violated (e.g., trying to ship an item that is out of stock). - Best Practice: Always provide a clear, actionable message. Instead of saying "Error occurred," say "The quantity to ship cannot exceed the quantity available in inventory."
Using AssertError for Testing
In your test codeunits, you cannot simply let an error crash your test. You use AssertError to verify that your code correctly throws an error when it is supposed to.
[Test]
procedure TestNegativeQuantity()
var
Item: Record Item;
begin
// We expect the code to fail if quantity is negative
AssertError SetQuantity(-5);
end;
The TryFunction Pattern
Sometimes you want to attempt an operation that might fail, but you don't want to crash the whole process. For example, if you are calling an external web service, the service might be down. You don't want to lose the user's work just because an external API timed out.
A TryFunction is a procedure marked with the [TryFunction] attribute. If an error occurs inside this procedure, it does not stop the execution of the calling code. Instead, the function returns a boolean false, and you can decide how to handle the situation.
[TryFunction]
procedure TryCallExternalService(Url: Text)
begin
// Perform web service call
// If this fails, the code continues in the caller
end;
procedure ExecuteProcess()
begin
if not TryCallExternalService('https://api.example.com') then
Message('The external service is currently unavailable. Please try again later.');
end;
Warning: The Scope of TryFunctions A
TryFunctionrolls back the changes made within that function if an error occurs. However, it does not undo changes made before the function was called. Use this pattern carefully to ensure that your database remains consistent even if aTryFunctionfails halfway through a business process.
Not read yet
Part 4: Best Practices for Error Management
Building robust applications requires a consistent strategy for how you interact with the user and the system. Follow these industry-standard practices to ensure your extensions are maintainable.
1. Fail Fast
Do not perform expensive calculations or database operations before checking if the input is valid. If a user enters a negative date, stop the code immediately at the very beginning of the function. This saves server resources and prevents the risk of "dirty" data reaching the database.
2. User-Centric Messaging
Avoid technical jargon in error messages. A user does not need to know that a RecordRef failed to open; they need to know that "The record you are trying to access has been deleted by another user." Use the StrSubstNo function to inject relevant data into your error messages so the user knows exactly which record caused the issue.
3. Avoid Over-using TryFunctions
While TryFunction is powerful, it can lead to "swallowed" errors where problems are hidden from the developer. Only use TryFunctions for operations that are genuinely outside the control of the AL code, such as network requests, external file access, or complex integrations. Never use them to hide bugs in your own logic.
4. Logging and Telemetry
In a cloud environment, you cannot always see what the user sees. Use the Session.LogMessage function to send diagnostic information to the Application Insights telemetry stream. This allows you to monitor for errors in production and fix them before users even report them.
Not read yet
Part 5: Comparison of Error Handling Techniques
When deciding how to handle a potential failure, use this table to choose the right approach.
| Technique | When to Use | Result of Failure |
|---|---|---|
Error() |
Validation of business rules, data integrity checks. | Transaction rolls back, stops execution, alerts user. |
[TryFunction] |
External calls, file I/O, integrations. | Returns false, allows graceful recovery. |
Confirm() |
Asking for user consent before a destructive action. | User chooses to continue or cancel, no error thrown. |
TestField() |
Checking if a field has a value or meets a condition. | Similar to Error(), but specifically for record fields. |
Part 6: Common Pitfalls and How to Avoid Them
Pitfall 1: Unhandled Record Locks
AL automatically locks records when you modify them. If you run a long-running process that locks a table, other users will experience delays. If an error occurs, the lock is released, but if your code is inefficient, you might be causing performance issues before the error even happens.
- Avoidance: Keep transactions short. Use
Clear()on variables that are no longer needed to free up memory and locks.
Pitfall 2: The "Silent Fail"
Developers sometimes write code that checks a condition and simply does nothing if the condition is not met, without notifying the user.
- Avoidance: If an action is expected to happen, but the conditions aren't met, always provide feedback. If the user clicks "Post" and nothing happens, they will assume the system is broken.
Pitfall 3: Improper use of Commit
The Commit function forces the current transaction to save to the database. This is dangerous because it makes the transaction permanent, meaning you can no longer roll it back if an error occurs later.
- Avoidance: Avoid using
Commitunless absolutely necessary (e.g., when you need to start a background session). Rely on the platform's automatic transaction management.
Not read yet
Part 7: Step-by-Step: Creating a Robust Validation Pattern
Let’s walk through a common requirement: validating a customer's credit limit before allowing a sale.
- Define the trigger point: Identify where the validation should occur (usually in the
OnValidatetrigger of a field or aBeforePostevent). - Gather the data: Retrieve the necessary records (Customer, Sales Header).
- Perform the check: Use
TestFieldfor simple checks or anifstatement for complex logic. - Provide clear feedback: If the check fails, use
Errorwith a descriptive message.
// Example: Validating credit limit
trigger OnValidate()
var
Customer: Record Customer;
begin
if not Customer.Get(Rec."Sell-to Customer No.") then
exit;
// Check if credit limit is exceeded
if (Customer."Credit Limit (LCY)" > 0) and
(Customer."Balance (LCY)" + Rec.Amount > Customer."Credit Limit (LCY)") then
begin
Error('The sale would exceed the credit limit for customer %1. Current balance: %2, Limit: %3',
Customer."No.", Customer."Balance (LCY)", Customer."Credit Limit (LCY)");
end;
end;
This pattern is effective because it is localized, uses standard fields, and provides the user with the exact numbers they need to understand why the system is blocking them.
Not read yet
Part 8: Advanced Error Handling: The ErrorBehavior
In newer versions of Business Central, you have more control over how errors are handled in specific contexts. For instance, when running reports or processing batch jobs, you may want to collect all errors instead of stopping at the first one.
- Error Message Object: You can use the
ErrorMessageobject to collect multiple errors and present them to the user in a list at the end of a process. This is much more user-friendly than having a process fail 10 times, forcing the user to fix one error, re-run, fail again, and so on.
Callout: The User Experience of Error Lists When building batch processes, avoid the "one-error-at-a-time" cycle. By using the
ErrorMessageobject, you can validate an entire batch of invoices and present a summary report. This allows the user to address all data issues in a single pass, significantly increasing their productivity.
Not read yet
Part 9: Summary and Key Takeaways
As you continue your journey in AL development, remember that the goal is not just to make the code run, but to make it behave predictably under all circumstances. Business Central is a platform that rewards developers who respect its transactional nature and provide clear, helpful feedback to the users.
Key Takeaways for Your Development Workflow:
- Prefer Built-ins: Always check the AL standard library before writing custom logic for dates, strings, or math. It is safer, faster, and more maintainable.
- Transaction Integrity: Understand that
Error()is a rollback mechanism. Use it to protect your data from invalid states, not just to display messages. - Use
TryFunctionResponsibly: Only use it for external dependencies that you cannot control, and always handle thefalsereturn value. - Actionable Feedback: Error messages should tell the user what happened and, if possible, how to fix it. Avoid technical jargon that confuses the business user.
- Fail Fast: Validate inputs at the start of your procedures to prevent unnecessary processing and database hits.
- Telemetry is Essential: Use
LogMessageto track errors in production. You cannot fix what you cannot see. - Avoid
Commit: Let the platform manage transactions. Manual commits are a frequent source of data inconsistency and hard-to-debug issues.
By internalizing these principles, you will move from writing simple scripts to engineering professional-grade solutions that integrate into the Business Central ecosystem effectively. Always test your error paths as rigorously as you test your success paths; in the world of ERP, the way your system handles a failure is often the most important feature you can build.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820