4 ms·
I mean... If you don't like writing `if err!=nil {...}` throughout your code base surely you can just create some middleware function in its own package that h
by patientplatypus 7y ago
I mean...
If you don't like writing `if err!=nil {...}` throughout your code base surely you can just create some middleware function in its own package that has switch statements based on error cases. Checking for errors frequently in the running of the code is more or less a Good Thing.
- mevile 7y agoI don't see how a switch statement helps you avoid checking for errors when methods you use return errors, and a lot of methods return errors.
- patientplatypus 7y agoYou can pass functions to functions (https://play.golang.org/p/XNMtrDUDS0 https://play.golang.org/p/XNMtrDUDS0). So you can do (sans syntax): ErrorCheckerFunc(fn myParams -> MyFunc(myParams), "message") ErrorCheckerFunc(fn myParams2 -> MyFunc2(myParams2), "message2") etc... and then the actual function: ErrorCheckerFunc(fn myFunc, message){ returnVal, returnError = myFunc(); switchError: case error is foo: print error case error is bar: log error print "error logged" ... case n+1 etc // you can handle message in a similar way to get // cases by function names, and if you have elixir // style quote unquote metaprogramming in Golang you might just be able to get function names based on passed function - I don't think this is in the language spec though it may be possible to do some other way. if error not nil do switchError(error) return RuhRoh else return returnVal } It's not so bad, it's just a middleware.
- djur 7y agoI'm not clear on what exactly you're trying to represent here, but it looks like something that wouldn't work with Go's type system. ErrorCheckerFunc would need to always have the same return type and accept a function with the same type signature.
- akavi 7y agoIf only there was a way to make a single function work with multiple different types. A way to "genericize" it, you might say. Alas, that's obviously completely impossible. Such a thing is beyond the capabilities of us mortal programmers. But maybe one day PL researchers will discover a way. One day...
- thatswrong0 7y agoRob Pike would rather use a for loop than map or filter.. so yeah don’t dream too big https://github.com/robpike/filter https://github.com/robpike/filter
- mevile 7y agoThat's kind of awesome code though. I learned things about go looking through how he implemented reduce. Thank you for sharing it.
- nkozyra 7y agoI see this a lot in example code and I hate it. Don't hand off error handling to some other function, return then and there, bubbling up whatever went wrong. Most of the time the receiver is swallowing the error or spitting it to stdout, so why bother