Skip to content

Commit 39b94a0

Browse files
committed
[files] Detailed error message for fopen
1 parent 34298bc commit 39b94a0

File tree

1 file changed

+17
-8
lines changed
  • modules/main/src/main/java/com/annimon/ownlang/modules/files

1 file changed

+17
-8
lines changed

modules/main/src/main/java/com/annimon/ownlang/modules/files/files.java

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -124,16 +124,18 @@ private static class fopen implements Function {
124124

125125
@Override
126126
public Value execute(Value[] args) {
127-
Arguments.checkAtLeast(1, args.length);
127+
Arguments.checkOrOr(1, 2, args.length);
128128

129129
final File file = Console.fileInstance(args[0].asString());
130130
try {
131-
if (args.length > 1) {
132-
return process(file, args[1].asString().toLowerCase());
133-
}
134-
return process(file, "r");
131+
final String mode = (args.length == 2)
132+
? args[1].asString().toLowerCase()
133+
: "r";
134+
return process(file, mode);
135135
} catch (IOException ioe) {
136-
return NumberValue.MINUS_ONE;
136+
final int key = -files.size() - 1;
137+
files.put(key, new FileInfo(ioe.getMessage()));
138+
return NumberValue.of(key);
137139
}
138140
}
139141

@@ -167,8 +169,10 @@ private abstract static class FileFunction implements Function {
167169
public Value execute(Value[] args) {
168170
if (args.length < 1) throw new ArgumentsMismatchException("File descriptor expected");
169171
final int key = args[0].asInt();
172+
final FileInfo fileInfo = files.get(key);
173+
if (key < 0) throw new ArgumentsMismatchException(fileInfo.error);
170174
try {
171-
return execute(files.get(key), args);
175+
return execute(fileInfo, args);
172176
} catch (IOException ioe) {
173177
return NumberValue.MINUS_ONE;
174178
}
@@ -578,12 +582,17 @@ private static Function fileToBoolean(FileToBooleanFunction f) {
578582

579583
private static class FileInfo {
580584
File file;
585+
String error;
581586
DataInputStream dis;
582587
DataOutputStream dos;
583588
BufferedReader reader;
584589
BufferedWriter writer;
585590

586-
public FileInfo(File file, DataInputStream dis, DataOutputStream dos, BufferedReader reader, BufferedWriter writer) {
591+
FileInfo(String errorMessage) {
592+
this.error = errorMessage;
593+
}
594+
595+
FileInfo(File file, DataInputStream dis, DataOutputStream dos, BufferedReader reader, BufferedWriter writer) {
587596
this.file = file;
588597
this.dis = dis;
589598
this.dos = dos;

0 commit comments

Comments
 (0)