Reputation: 41
I am writing a monitor program that will merge into company's system. When the program running, seldom panicked some error since a variety of problem such as a few other's server doesn't obtain the rule of http, network error or anything else.I fix most of them but I am still afraid of influence on the master program by possibly potential errors.
From company's aspect, the stability of master program is most important, secondly, monitoring's result, the stability of monitoring is low-priority.
Is there have a method can isolate error? For example,"try...except Exception..." in python to ignore error(Admittedly, Not recommended)How to avoid effect other code when panic error or something else in golang
Upvotes: 3
Views: 1110
Reputation: 12675
User recover function at the top of your function in which you have the chances of getting error. Don't use panic
as it will stop the execution of your code. Use below code snippet. Also It will print the log which will let you know in which function the exception occurred.
defer func() {
if r := recover(); r != nil {
log.Println("Recovered in custom function", r)
}
}()
Upvotes: 1
Reputation: 49
With panics, you can use recover like this
func recoverExample() {
defer func() {
if panicMessage := recover(); panicMessage != nil {
fmt.Printf("Panic '%v' captured", panicMessage)
}
}()
panic("Oh no!")
}
With output:
Panic 'Oh no!' captured
Upvotes: 3