Custom Errors in OpenSCAD

In OpenSCAD, we can create custom errors by defining our own error functions. Here’s an example that demonstrates how to create and use custom errors:

// A custom error function
function argError(arg, message) = [arg, message];

// Function that may return a custom error
function f(arg) =
    arg == 42 ? argError(arg, "can't work with it") :
    arg + 3;

// Main function to demonstrate error handling
function main() =
    let(result = f(42))
    is_list(result) && len(result) == 2 ?
        let(
            arg = result[0],
            message = result[1]
        )
        str("Error: ", arg, " - ", message)
    :
    str("Result: ", result);

// Execute the main function and echo the result
echo(main());

In this OpenSCAD example:

  1. We define a custom error function argError that takes an argument and a message.

  2. The f function demonstrates how to return a custom error. If the input is 42, it returns our custom error; otherwise, it returns the input plus 3.

  3. The main function shows how to handle the custom error. It calls f(42) and checks if the result is a list (our custom error structure).

  4. If it’s an error, we extract the argument and message from the result and format an error string.

  5. If it’s not an error, we simply return the result.

  6. Finally, we use echo to display the result of the main function.

To run this program, save it as a .scad file and open it in OpenSCAD. The console output will show:

ECHO: "Error: 42 - can't work with it"

This demonstrates how we can implement and use custom errors in OpenSCAD, even though the language doesn’t have built-in error handling mechanisms like try-catch blocks.

Note that OpenSCAD’s functional nature and lack of traditional error handling makes this approach quite different from languages with exception handling. However, this pattern allows us to create and propagate custom errors in a functional style.