github.com/richardwilkes/toolbox@v1.121.0/errs/recovery.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package errs
    11  
    12  // RecoveryHandler defines the callback used when panics occur with Recovery.
    13  type RecoveryHandler func(error)
    14  
    15  // Recovery provides an easy way to run code that may panic. 'handler' will be called with the panic turned into an
    16  // error. Pass in nil to silently ignore any panic.
    17  //
    18  // Typical usage:
    19  //
    20  //	func runSomeCode(handler errs.RecoveryHandler) {
    21  //	    defer errs.Recovery(handler)
    22  //	    // ... run the code here ...
    23  //	}
    24  func Recovery(handler RecoveryHandler) {
    25  	if recovered := recover(); recovered != nil && handler != nil {
    26  		err, ok := recovered.(error)
    27  		if !ok {
    28  			err = Newf("%+v", recovered)
    29  		}
    30  		defer Recovery(nil) // Guard against a bad handler implementation
    31  		handler(NewWithCause("recovered from panic", err))
    32  	}
    33  }