Home  >  Article  >  Backend Development  >  How to Return an Error if a Go Function Panics?

How to Return an Error if a Go Function Panics?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 00:39:03215browse

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.

The above is the detailed content of How to Return an Error if a Go Function Panics?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn