Using the Assert Helper

Using the assert() helper method

The assert() helper method allows you to validate conditions and throw exceptions if they fail. It's useful for:

  • Checking pre-conditions before processing

  • Validating method arguments

  • Ensuring business logic invariants

The assert() method was introduced in 4.3.1.

Overview

The assert() method mimics Java's assert keyword. It evaluates a condition to a boolean and must be true to pass. If false or null, it throws an AssertError exception.

Basic Usage

assertions.bx
function processOrder(orderId) {
    // Assert that orderId is provided
    assert(orderId > 0, "Order ID must be greater than 0");

    var order = orderService.getById(orderId);

    // Assert that order exists
    assert(!isNull(order), "Order not found");

    // Assert order is in correct status
    assert(order.status == "pending", "Order must be pending to process");

    // Process the order
    return processPayment(order);
}

Syntax

Parameters:

  • target - The value to evaluate as boolean (required)

  • message - Custom error message (optional)

Returns: true if assertion passes

Throws: AssertError if assertion fails

Return Values

Common Patterns

Null Checking

Range Validation

Array/Collection Validation

State Validation

API Input Validation

Assert vs Validate

Choose the right tool for the job:

Use assert() when:

  • Checking pre-conditions before processing

  • Validating method arguments

  • Ensuring business logic invariants

  • You want quick fail-fast behavior

  • Condition is simple and boolean

Use validate() when:

  • Validating complex objects with multiple rules

  • Collecting multiple errors from one check

  • Validating form data or user input

  • You need detailed error messages and fields

  • Working with constraint definitions

Error Handling

Catching AssertError

Best Practices

1. Use Clear, Specific Messages

2. Fail Fast

Check conditions as early as possible in your function:

3. Don't Overuse Assert

Assertions are for programmer errors, not user input:

4. Use for Invariants

Assert the state that should always be true:

See Also

Last updated

Was this helpful?