How to Return an Error if a Go Function Panics?

Linda Hamilton
Release: 2024-11-12 00:39:03
Original
223 people have browsed it

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...
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template