PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How do I handle errors in a deferred function?

 November 14, 2022     deferred, error-handling, go, panic     No comments   

Issue

func someFunc() (err error) {
    defer func(err_ error) {
        r.handleErrOrPanic(err_, obj) 
    }(err) // err is always nil here
    err = ThrowErrOrPanic(ctx, obj)
    return err
}

I would like to use handleErrOrPanic as a deferred function to handle the error or the panic. I have to define it before ThrowErrOrPanic, since the deferred function has to handle the panic. However, if I define it before err is always nil. How do I solve this?


Solution

In the deferred func use the named return value of the surrounding function, i.e. use err not err_. If you got panic and you want to recover from it use recover() in the deferred func.

func someFunc() (err error) {
    defer func() {
        if x := recover(); x != nil { // panic occurred?
            // handle panic
        } else if err != nil { // a plain error occurred?
            // handle error
        } else {
            // all good
        }
    }()

    err = ThrowErrOrPanic(ctx, obj)
    return err
}

https://go.dev/play/p/miTr-lN1Y9R



Answered By - mkopriva
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing