import ballerina/io;
// Converts `bytes` to a `string` value and then to an `int` value.
function intFromBytes(byte[] bytes) returns int|error {
string|error ret = string:fromBytes(bytes);
// The `is` operator can be used to distinguish errors
// from other values.
if ret is error {
return ret;
} else {
return int:fromString(ret);
}
}
// The `main` function can return an `error` value.
public function main() returns error? {
int|error res = intFromBytes([104, 101, 108, 108, 111]);
if res is error {
// The `check` expression is the shorthand for this pattern of
// checking if a value is an `error` value and returning that value.
return res;
} else {
io:println("result: ", res);
return;
}
}
Error handlingUsually, a function handles errors by passing them up to its caller.
The |
import ballerina/io;
function intFromBytes(byte[] bytes) returns int|error {
Converts bytes
to a string
value and then to an int
value.
string|error ret = string:fromBytes(bytes);
if ret is error {
The is
operator can be used to distinguish errors
from other values.
return ret;
} else {
return int:fromString(ret);
}
}
public function main() returns error? {
The main
function can return an error
value.
int|error res = intFromBytes([104, 101, 108, 108, 111]);
if res is error {
return res;
The check
expression is the shorthand for this pattern of
checking if a value is an error
value and returning that value.
} else {
io:println("result: ", res);
return;
}
}
bal run error_handling.bal
error: {ballerina/lang.int}NumberParsingError {"message":"'string' value 'hello' cannot be converted to 'int'"}