Using named return variables to capture panics in Go

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

This is going to be a short post inspired by Sean Kelly's tweet in November.

I found a reason to use named returns in #golang and now I feel pic.twitter.com/6EN3vapuHB

— Sean Kelly (@StabbyCutyou) November 15, 2017

The goal is to just document and illustrate a situation where named return variables are necessary, so with that said let's just jump right in.

Imagine you are writing some code that uses a function that can panic, and for whatever reason (3rd party lib, backwards compatibility, etc) you can't change that function.

func pressButton() {    fmt.Println("I'm Mr. Meeseeks, look at me!!")  // other stuff then happens, but if Jerry asks to   // remove 2 strokes from his golf game...  panic("It's gettin' weird!")}

You still need to use that function, but if it panics you want to capture the panic and return it as an error so you write some code like this:

func doStuff() error {    var err error  // If there is a panic we need to recover in a deferred func  defer func() {    if r := recover(); r != nil {      err = errors.New("the meeseeks went crazy!")    }  }()  pressButton()  return err}

Run it on the Go Playground - https://play.golang.org/p/wzkjKGqFPL

Then you go run your code and... what's this? Your error is nil even when the code panics? That's not what we wanted!

Why does this happen?

While at first it looks like our code is returning the var err error that we create at the start of our function, the truth is our program never gets to that line of code. This means it never actually returns that specific err variable, and altering it inside of our deferred function ends up being pointless.

Adding a Println after the call to pressButton but before the return really helps illustrate this:

pressButton()  // Nothing below here gets executed!fmt.Println("we got here!")  return err  

Run it on the Go Playground - https://play.golang.org/p/Vk0DYs20eB

How do we fix it?

To fix this issue, we can simply use a named return variable.

func doStuff() (err error) {      // If there is a panic we need to recover in a deferred func    defer func() {        if r := recover(); r != nil {            err = errors.New("the meeseeks went crazy!")        }    }()    pressButton()    return err}

Run it on the Go Playground - https://play.golang.org/p/bqGOroPjQJ

The resulting code looks very similar, but by naming our return variable when we declare the function our program will now return the err variable even if we never hit the return statement at the end of our doStuff function. Because of this minor difference, we can now alter the err variable inside of our deferred function and successfully capture the panic.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.