by userbinator · 7y ago · 0 comments
I've thought about this problem too (error handling in general), and with that hint of this being a "chain", arrived at this solution which I think is extremely concise and elegant:
if((err = func1()) ||
(err = func2()) ||
(err = func3()) ||
(err = func4()) ||
...
) {
/* handle the error */
}
or if you want to get more fancy and know which step failed, int step = 0;
if((step++, err = func1()) ||
(step++, err = func2()) ||
(step++, err = func3()) ||
(step++, err = func4())
) {
...
Of course this can be modified suitably if your error vs. success values are different, but the structure is the same: a chain of actions one after another, broken only by short-circuit evaluation. It's surprising that this pattern isn't seen more, because I've shown this to a few others and the response has almost always been an initial puzzlement followed by "wow, that's extremely neat" or "why didn't I think of that?" This is certainly an example of "use the language". func (r *Resource) get(w http.ResponseWriter, r *http.Request){
user, err := r.authenticate(req)
if err != nil {
r.WriteJSONErr(w, err)
return
}
var records []*User
if err := r.db.Select("select id, name, created_date from users", &records); err != nil {
r.WriteJSONErr(w, err)
return
}
r.WriteJSON(w, records)
}
You would have to reformat all your function signatures to receive maybe a pointer to populate and return only an error, which could work but meh. (f = fopen(filename, "rb")) &&
...
(ptr = malloc(size)) &&
fread(ptr, 1, size, f) == size &&
...https://github.com/blockassets/bam_agent/blob/master/tool/ht...
I would like to counter with my C++ way of doing error handling without exceptions:
if (!func1()) return false;
if (!func2()) return false;
if (!func3())
{
err = get_error();
...
}
if (!func4()) return false;
Each function sets a global exception-like error object which can be
inspected by the caller if the function signaled an error (like
returning false in this example):Of course you need thread local variables for this. Not sure if this is a problem for Go or in general...
If you want to do something with the intermediate results (e.g, the functions return more than just error) this will not be possible..
resourceName, err := connection.getName()
if err != nil {
// handle
}
fst := strings.Split(resourceName, ".")[0]
sendTime, err := connection.findSendtime(fst)
if err != nil {
// handle
}
// do something with sendtime and call new func.. you get the point
EDIT: Fix some mistakes in my example code. Obviously fake example though :)Hope you're proud of yourself, lol.