"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Return an Error if a Go Function Panics?

How to Return an Error if a Go Function Panics?

Published on 2024-11-18
Browse:753

How to Return an Error if a Go Function Panics?

Returning from Defer in Go

You're encountering an issue where you want to return an error if a function panics in Go. Here's an analysis and a fix for your code:

func getReport(filename string) (rep report, err error) {
    rep.data = make(map[string]float64)

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
            switch x := r.(type) {
            case string:
                err = errors.New(x)
            case error:
                err = x
            default:
                err = errors.New("Unknown panic")
            }
            rep = nil // Invalidate rep
        }
    }()
    panic("Report format not recognized.")
    // rest of the getReport function...
}

Concept of Panic and Defer

  • Panic: A panic signals a runtime error that can be caught by a recover in a defer function.
  • Defer: A defer statement delays the execution of a function until the surrounding function exits.

Modifications in the Code:

  • The defer function now uses switch-case statements to handle the recovered value correctly.
  • If the recovered value is a string, it's converted to an error using errors.New().
  • The rep variable is invalidated after an error encounter to ensure it doesn't return any data.
  • The rep variable is returned as nil in case of an error, which matches your original function signature.

With these changes, your getReport function will return an error if it panics due to an invalid report format. The error message will be either the panic value (if a string) or a generic error indicating an unknown panic.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3