Golang Panic Prevention

In Golang, panic without recovery will cause the process to crash, so at the beginning of each function, I insert the following code fragment:

defer func() { if err := recover(); err != nil { fmt.Println(err) } }() 

just to prevent my program from crashing. Now I wonder if this is really the way to go? Because I think it's a little strange to put the same code everywhere.

It seems to me that the Java path that overlaps exceptions to the calling function is until the main function becomes the best way to manage exceptions / panic. I understand this from the Go design, but what is the advantage of an immediate process failure, like what Go does?

+6
source share
2 answers

You should only recover from panic if you know exactly why. The Go program will panic essentially in two circumstances:

  • Program logic error (for example, turning a pointer to zero or external access or access to a slice)
  • Intentional panic (called using panic(...) ) from your code or the code that your code calls

In the first case, the crash is appropriate, because it means that your program has entered a bad state and should not continue to execute. In the second case, you should only recover from panic if you expect it. The best way to explain this is to simply say that it is very rare, and you will recognize this case if you see it. I am pretty sure that no matter what code you write, you do not need to recover from a panic.

+5
source

As a rule, even with exceptions, you catch them on the "FaultBarrier". Usually this is the place where all new threads appear. The point is to catch and log unexpected failures.

In Go, you use return values ​​for all expected failures. The framework in which you work typically has an error limit to catch a session (i.e., usually an http transaction) and log the problem. The only other place that I see in the recovery process is things like the non-idempotent Close function. If you have a situation where you cannot say that something is already closed, but you know that it should be closed, then you can finish the recovery so that the second closed panic is ignored, instead of failing what you do up to the FaultBarrier level.

+1
source

Source: https://habr.com/ru/post/973951/


All Articles