Created
December 31, 2019 10:07
-
-
Save MaryamZi/a21ebd7602cf491df3066d92bbf519cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ballerina/io; | |
const MY_REASON = "MyReason"; | |
type MyDetail record {| | |
string message; | |
error cause?; | |
int code?; | |
anydata|error...; | |
|}; | |
type MyError error<MY_REASON, MyDetail>; | |
function foo() returns error? { | |
return MyError(message = "err message", code = 123, bar = 12.3); | |
} | |
public function main() { | |
// Say I call a function returning either an `error` or `()`. | |
error? res = foo(); | |
if res is MyError { | |
// Assume if the value is of type `MyError`, I want to access the error | |
// reason and the `message`, `code`, and `priority` fields from | |
// the detail if present. | |
// A reason is always present and is a string. | |
// Thus, we use a `string` variable for the reason. | |
string errReason; | |
// `message` is a mandatory field in `MyError`'s detail, | |
// Thus, we use a `string` variable for `message`. | |
string errMessage; | |
// `code` is an optional field of type `int` in `MyError`'s detail, | |
// Thus, we use an `int?` variable for `code`. | |
int? errCode; | |
// `priority` if present would be part of the rest | |
// field of the error detail, which is of type `anydata|error`. | |
// Since `()` (representing the absence) is already part of | |
// `anydata`, we use a variable of type `anydata|error`. | |
anydata|error errPriority; | |
// Using a destructuring binding pattern with the error variable of | |
// type `MyError`. | |
error(errReason, message = errMessage, code = errCode, priority = errPriority) = res; | |
io:println("errReason: ", errReason); // MyReason | |
io:println("errMessage: ", errMessage); // err message | |
io:println("errCode is int: ", errCode is int); // true | |
io:println("errPriority is (): ", errPriority is ()); // true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment