[m-users.] io.error type
Volker Wysk
post at volker-wysk.de
Fri Feb 4 21:50:54 AEDT 2022
Am Freitag, dem 04.02.2022 um 10:49 +0100 schrieb fabrice nicol:
> > > > I want to read the contents of a file, using open_input,read_file_as_string, close_input. In case the file doesn't exist, I want toreturn an empty string. So, in case of an error, I want to determine if it'sbecause the file doesn't exist.It isn't a show stopper to me, I can return "" in case of any error, but itisn't optimal.Cheers,Volker
> > > Why do you need to test according to io.error?
> > > io.error will only "materialize" logical failure. Which takes place further up in the tree.
> > I don't get it.
> This looks clear to me at least. io.error does not pop up out of thin air.
> You get an io.error when there is an error in open_input. In the snippet I sent, when there is an error on opening the file,
> OpenInputResult = ok(InputStream)
> fails. Then the other branch of the disjunct is processed and you get the error message through:
> OpenInputResult = error(OpenInputError)
> Now, there is no use testing against io.error, as long as you can test against OpenInputResult, which is unified before the disjunction is processed (one node up relative to the nodes of the above disjunct unifications).
This is what I'm doing:
% Read an entire text file. Return the result and errors in an io.res.
:- pred contents(string::in, % File name
io.res(string)::out, % Result (the contents or an error)
io::di, io::uo)
is det.
contents(Filename, Res, !IO) :-
open_input(Filename, Res1, !IO),
(
Res1 = ok(Stream),
read_file_as_string(Stream, Res2 : io.maybe_partial_res(string), !IO),
(
Res2 = ok(Contents),
Res = ok(Contents)
;
Res2 = error(_, Err2),
Res = error(Err2)
),
close_input(Stream, !IO)
;
Res1 = error(Error : io.error),
Res = io.error(Error)
).
> > > So you just need to test against open_input out-mode argument values.
> > > Have you tried something along these lines?
> > I need to distinguish between "file does not exist" errors and other errors. I want the other errors stay errors, which will get reported later.
> In this case, you can return ReadInputError instead of ResultStr (or throwing an exception in the second disjunct after read_file_as_string).
> And analyse ReadInputError later (just modify my_pred accordingly).
No, you can't. The ReadInputError is of type io.error, and this is abstract. The only thing you can do with it, is to get an error message. That's the problem here.
Cheers, Volker
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mercurylang.org/archives/users/attachments/20220204/d3c813be/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.mercurylang.org/archives/users/attachments/20220204/d3c813be/attachment.sig>
More information about the users
mailing list