Skip to content

Instantly share code, notes, and snippets.

@MaryamZi
Last active December 24, 2019 10:15
Show Gist options
  • Save MaryamZi/3f3d84b2ae9aaf489d83867f52040d29 to your computer and use it in GitHub Desktop.
Save MaryamZi/3f3d84b2ae9aaf489d83867f52040d29 to your computer and use it in GitHub Desktop.
import ballerina/log;
const ERR_REASON_FILE_NOT_FOUND = "FileNotFound";
const ERR_REASON_INSUFFICIENT_PERMISSION = "InsufficientPermission";
// The detail type for `FileNotFoundError` defaults to the default detail type now.
type FileNotFoundError error<ERR_REASON_FILE_NOT_FOUND>;
type ErrDetail record {|
string message?;
error cause?;
int code; // an additional mandatory `int` code
// no additional fields
|};
// Uses the custom detail type.
type InsufficientPermissionError error<ERR_REASON_INSUFFICIENT_PERMISSION, ErrDetail>;
// The return type now mentions the individual errors.
function deleteFile(string file) returns FileNotFoundError|InsufficientPermissionError? {
if !isFileExists(file) {
// Create an error of the custom type and return it.
FileNotFoundError err = error(ERR_REASON_FILE_NOT_FOUND);
return err;
}
if !canDelete(file) {
// Uses the indirect error constructor, which allows omitting the reason since
// it can only be one constant value.
return InsufficientPermissionError(code = 998877);
}
// Delete the file.
}
function isFileExists(string file) returns boolean {
boolean fileExists = false;
// insert existence check logic
return fileExists;
}
function canDelete(string file) returns boolean {
boolean canDelete = false;
// insert permission check logic
return canDelete;
}
public function main() {
FileNotFoundError|InsufficientPermissionError? res = deleteFile("foo.txt");
// If either a `FileNotFoundError` or an `InsufficientPermissionError` is
// return the type test evaluates to true.
if res is error {
log:printError("Error deleting file", res);
return;
}
// Continue subsequent logic.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment