import ballerina/io;

// Convert bytes to a string and then to an int.
function intFromBytes(byte[] bytes) returns int|error {
    string|error ret = string:fromBytes(bytes);

    // The `is` operator can be used to distinguish errors
    // from others value.
    if ret is error {
        return ret;
    } else {
        return int:fromString(ret);
    }
}

// The `main` function can return an error.
public function main() returns error? {
    int|error res = intFromBytes([104, 101, 108, 108, 111]);    
    if res is error {
        // The `check` expression is shorthand for this pattern of
        // checking if a value is an error and returning that value.
        return res;

    } else {
        io:println("result: ", res);
    }
}

Error Handling

Usually, a function handles errors by passing them up to its caller. The main function can also return an error.

import ballerina/io;
function intFromBytes(byte[] bytes) returns int|error {
    string|error ret = string:fromBytes(bytes);

Convert bytes to a string and then to an int.

    if ret is error {
        return ret;
    } else {
        return int:fromString(ret);
    }
}

The is operator can be used to distinguish errors from others value.

public function main() returns error? {
    int|error res = intFromBytes([104, 101, 108, 108, 111]);    
    if res is error {

The main function can return an error.

        return res;

The check expression is shorthand for this pattern of checking if a value is an error and returning that value.

    } else {
        io:println("result: ", res);
    }
}
bal run error_handling.bal
error: {ballerina/lang.int}NumberParsingError {"message":"'string' value 'hello' cannot be converted to 'int'"}