N
N
NubasLol2019-11-19 20:04:49
go
NubasLol, 2019-11-19 20:04:49

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
  }

Very visually spoils controllers and code readability

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Rybas, 2019-11-20
@NubasLol

You can use panic/recoverand 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
}

D
Dmitry Shitskov, 2019-11-19
@Zarom

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.

M
Mikhail Osher, 2019-11-19
@miraage

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 question

Ask a Question

731 491 924 answers to any question