Answer the question
In order to leave comments, you need to log in
How to get rid of such code duplication?
Let's say a controller method, and there are as many as 4 places where an error can occur. And everywhere you have to write its processing
if err != nil {
log.Println(err)
internalhttp.NewJsonResponse().ErrorResponse(w, err)
return
}
Answer the question
In order to leave comments, you need to log in
You can use panic/recover
and modify the returned parameters (if you still need to return an error)
func myFunc() (err error) {
defer func() {
if r := recover(); r != nil {
log.Println(r)
internalhttp.NewJsonResponse().ErrorResponse(w, r)
err = r.(error)
}
}()
...
if err := myOtherFunc(); err != nil {
panic(err)
}
return
}
That's the philosophy of go - explicit error handling. Of course, you can also write on panic-recover, but it will be no less ugly and not the fact that it is productive. Just get used to it, accept it as a feature of the language.
You can pass identical lines to some ErrorHandler function.
I haven't coded much in Go, but I'm interested in the language.
All the friends who write in Go say that there is no other way.
The language was originally conceived as "stupid", but fast.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question