uber-go / dig

A reflection based dependency injection toolkit for Go.
https://go.uber.org/dig
MIT License
3.78k stars 206 forks source link

Opt-In Panic Recovery #364

Closed JacobOaks closed 1 year ago

JacobOaks commented 1 year ago

Currently, when a panic occurs in provided/invoked/decorated functions, the message users see can be very unwieldy, especially with complicated dependency graphs.

This change allows us to construct our container with a new Option called RecoverFromPanics():

c := dig.New(dig.RecoverFromPanics())

When this is done, any panics that occur in provided/invoked/decorated functions will be recovered from, and wrapped in a new error Type, PanicError, containing the relevant function and the panic value. This PanicError will then be dealt with as a normal error when propagated back us, meaning panics would be just as readable as normal errors when dealing with long complicated call chains.

When opted in, we can distinguish panics from dig errors and non-dig errors when calling c.Invoke like so:

if err := c.Invoke(myFunc); err != nil {
    rootCause := dig.RootCause(err)
    var pe dig.PanicError
    var de dig.Error
    if errors.As(rootCause, &pe) {
        // This was originally a panic, look at pe.Panic
    } else if errors.As(rootCause, &de) {
        // This is a Dig error
    } else {
        // This is just an error from my functions
    }
}

Or, if we just want to distinguish panics from errors we can simply check errors.As(err, &pe).

codecov[bot] commented 1 year ago

Codecov Report

Merging #364 (eca90af) into master (cbba855) will increase coverage by 0.03%. The diff coverage is 100.00%.

:exclamation: Current head eca90af differs from pull request most recent head 1aa3b92. Consider uploading reports for the commit 1aa3b92 to get more accurate results

@@            Coverage Diff             @@
##           master     #364      +/-   ##
==========================================
+ Coverage   98.30%   98.33%   +0.03%     
==========================================
  Files          21       21              
  Lines        1414     1441      +27     
==========================================
+ Hits         1390     1417      +27     
  Misses         15       15              
  Partials        9        9              
Impacted Files Coverage Δ
constructor.go 97.22% <100.00%> (+0.25%) :arrow_up:
container.go 100.00% <100.00%> (ø)
decorate.go 100.00% <100.00%> (ø)
error.go 100.00% <100.00%> (ø)
invoke.go 100.00% <100.00%> (ø)
scope.go 98.90% <100.00%> (+0.01%) :arrow_up:

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more