import ballerina/io;const ACCOUNT_NOT_FOUND = "AccountNotFound";
const INVALID_ACCOUNT_ID = "InvalidAccountID";function getAccountBalance(int accountID) returns int|error {
if (accountID < 0) {
return error(INVALID_ACCOUNT_ID, accountID = accountID);
} else if (accountID > 100) {
return error(ACCOUNT_NOT_FOUND, accountID = accountID);
}
return 600;
}public function main() {
error simpleError = error("SimpleErrorType", message = "Simple error occurred");
io:println("Error: ", simpleError.reason(),
", Message: ", simpleError.detail()?.message); int|error result = getAccountBalance(-1);
if (result is int) {
io:println("Account Balance: ", result);
} else {
io:println("Error: ", result.reason(),
", Account ID: ", result.detail()["accountID"]);
}
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run error_handling.bal
Error: SimpleErrorType, Message: Simple error occurred
Error: InvalidAccountID, Account ID: -1
Error HandlingBallerina distinguishes ordinary errors such as failing to open a file or failing to send a network response, from an exceptional condition in the code, such as type cast errors. Error handling in Ballerina incorporates two different strategies depending on the type of error. For ordinary errors such as failing to open a file or failing to send a network response, the error value is returned. When the Ballerina runtime encounters exceptional conditions the runtime panics resulting in abrupt completion of execution, unless the error is explicitly handled. Ballerina provides language constructs to handle both returned error values and panics. This example demonstrates how errors can be created, returned, and how returned errors can be handled. Ballerina error values are immutable structured values composed of an error reason string, a stack trace representing the execution stack at the point at which the error value was created, and an error detail record. |
|
|
|
|
|
|
|
Return an error with “InvalidAccountID” as the reason if |
|
Return an error with “AccountNotFound” as the reason if |
|
Return a value if |
|
|
|
Define an error of the generic |
|
Print the error reason and the |
|
|
|
If the |
|
If an error is returned, print the reason and the account ID from the detail record. Each additional error detail field provided to the error constructor is available as a field in the error detail record. |
|