1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
11 # Standard error-management infrastructure.
17 # Standard class for error messages
19 # A short human-readable error message.
21 # This message is short and informative and could be displayed on the console, a dialog-box
22 # or written in a log file.
24 # Message should be explicative, autonomous and do not depend on contextual information.
26 # Eg. instead of "Fatal error: cannot open file",
27 # something like "File error, cannot open /some/path/document.ext, file not found." is preferred,
28 # where the message is informative as it, and the severity of the error is not assumed:
29 # while fatal for the library, it could be something benign for the program.
32 # An original error that caused the creation of this error, if any.
34 # This is used to chain errors and track the implication of various sub-systems for a given error.
36 # When displaying an error the end user, causes can be recursively displayed.
37 var cause
: nullable Error = null is writable
39 redef fun to_s
do return message
42 # Helper class used as a return value of methods that may give errors instead of values.
44 # Functions that return useful values or errors could use it to simulate an easy-to use multiple-return.
47 # fun division(a,b: Int): MaybeError[Int, Error]
49 # if b == 0 then return new MaybeError[Int, Error](null, new Error("Arithmetic Error: try to divide {a} by 0"))
50 # return new MaybeError[Int, Error](a / b, null)
53 # assert division(10, 2).is_error == false
54 # assert division(10, 0).is_error == true
57 # Clients has to handle the error:
60 # var res = division(10, 2)
61 # if res.is_error then
66 # assert res.value == 5
68 class MaybeError[V
, E
: Error]
70 var maybe_value
: nullable V
73 var maybe_error
: nullable E
76 fun is_error
: Bool do return maybe_error
!= null
79 # REQUIRE: `not is_error`
80 fun value
: V
do return maybe_value
.as(V
)
84 fun error
: E
do return maybe_error
.as(E
)
88 if e
!= null then return e
.to_s