// Recovery returns a middleware which catch panics and log them
974386
func Recovery(debug bool) HandlerFunc {
	return func(ctx *Context) {
		defer func() {
			if e := recover(); e != nil {
				var buf bytes.Buffer
				fmt.Fprintf(&buf, "Handler crashed with error: %v", e)

				for i := 1; ; i++ {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					} else {
						fmt.Fprintf(&buf, "\n")
					}
					fmt.Fprintf(&buf, "%v:%v", file, line)
				}

				var content = buf.String()
				ctx.Logger.Error(content)

				if !ctx.Written() {
					if !debug {
						ctx.Result = InternalServerError(http.StatusText(http.StatusInternalServerError))
					} else {
						ctx.Result = InternalServerError(content)
					}
				}
			}
		}()

		ctx.Next()
	}
}
257975
func (p *parser) popRecovery() {
	// GC that map
	p.recoveryStack[len(p.recoveryStack)-1] = nil

	p.recoveryStack = p.recoveryStack[:len(p.recoveryStack)-1]
}
13737
func onRecover(e interface{}, info string) (err Error) {
	if e != nil {
		switch {
		case isSystemError(e):
			return e.(Error)
		case isGenericError(e):
			return newSystemErrorWithCause(info, e.(error))
		default:
			return newSystemErrorf(info+" - recovered: %s", e)
		}
	}
	return nil
}
50181
func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc {

	return func(c *gin.Context) {
		defer func() {
			flags := map[string]string{
				"endpoint": c.Request.RequestURI,
			}
			if rval := recover(); rval != nil {
				debug.PrintStack()
				rvalStr := fmt.Sprint(rval)
				client.CaptureMessage(rvalStr, flags, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)),
					raven.NewHttp(c.Request))
				c.AbortWithStatus(http.StatusInternalServerError)
			}
			if !onlyCrashes {
				for _, item := range c.Errors {
					client.CaptureMessage(item.Error(), flags, &raven.Message{
						Message: item.Error(),
						Params:  []interface{}{item.Meta},
					},
						raven.NewHttp(c.Request))
				}
			}
		}()

		c.Next()
	}
}
178387
func (c *MConnection) _recover() {
	if r := recover(); r != nil {
		err := cmn.ErrorWrap(r, "recovered panic in MConnection")
		c.stopForError(err)
	}
}
78008
func (_class VMClass) Recover(sessionID SessionRef, self VMRef, sessionTo SessionRef, force bool) (_err error) {
	_method := "VM.recover"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVMRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_sessionToArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_to"), sessionTo)
	if _err != nil {
		return
	}
	_forceArg, _err := convertBoolToXen(fmt.Sprintf("%s(%s)", _method, "force"), force)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg, _sessionToArg, _forceArg)
	return
}
535834
func Recoverer(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		reqID := GetReqID(*c)

		defer func() {
			if err := recover(); err != nil {
				printPanic(reqID, err)
				debug.PrintStack()
				http.Error(w, http.StatusText(500), 500)
			}
		}()

		h.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
622594
func (idx *SeriesIndex) Recover(segments []*SeriesSegment) error {
	// Allocate new in-memory maps.
	options := rhh.DefaultOptions
	options.Metrics = idx.rhhMetrics
	options.Labels = idx.rhhLabels
	options.MetricsEnabled = idx.rhhMetricsEnabled

	idx.keyIDMap = rhh.NewHashMap(options)
	idx.idOffsetMap = make(map[SeriesID]int64)
	idx.tombstones = make(map[SeriesID]struct{})

	// Process all entries since the maximum offset in the on-disk index.
	minSegmentID, _ := SplitSeriesOffset(idx.maxOffset)
	for _, segment := range segments {
		if segment.ID() < minSegmentID {
			continue
		}

		if err := segment.ForEachEntry(func(flag uint8, id SeriesIDTyped, offset int64, key []byte) error {
			if offset <= idx.maxOffset {
				return nil
			}
			idx.execEntry(flag, id, offset, key)
			return nil
		}); err != nil {
			return err
		}
	}
	return nil
}
849973
func (n *LevelLogger) Panic(v ...interface{}) {
	if !n.Enabled() {
		return
	}
	s := fmt.Sprint(v...)
	n.mu.RLock()
	n.logger.Output(callDepth, s)
	n.mu.RUnlock()
	panic(s)
}
644741
func RecoveryHandler(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
	return Recoverer(http.HandlerFunc(handler)).ServeHTTP
}
1066732
func (w *Wallet) recovery(startHeight int32) error {
	log.Infof("RECOVERY MODE ENABLED -- rescanning for used addresses "+
		"with recovery_window=%d", w.recoveryWindow)

	// We'll initialize the recovery manager with a default batch size of
	// 2000.
	recoveryMgr := NewRecoveryManager(
		w.recoveryWindow, recoveryBatchSize, w.chainParams,
	)

	// In the event that this recovery is being resumed, we will need to
	// repopulate all found addresses from the database. For basic recovery,
	// we will only do so for the default scopes.
	scopedMgrs, err := w.defaultScopeManagers()
	if err != nil {
		return err
	}
	tx, err := w.db.BeginReadWriteTx()
	if err != nil {
		return err
	}
	txMgrNS := tx.ReadBucket(wtxmgrNamespaceKey)
	credits, err := w.TxStore.UnspentOutputs(txMgrNS)
	if err != nil {
		tx.Rollback()
		return err
	}
	addrMgrNS := tx.ReadWriteBucket(waddrmgrNamespaceKey)
	err = recoveryMgr.Resurrect(addrMgrNS, scopedMgrs, credits)
	if err != nil {
		tx.Rollback()
		return err
	}

	// We'll also retrieve our chain backend client in order to filter the
	// blocks as we go.
	chainClient, err := w.requireChainClient()
	if err != nil {
		tx.Rollback()
		return err
	}

	// We'll begin scanning the chain from the specified starting height.
	// Since we assume that the lowest height we start with will at least be
	// that of our birthday, we can just add every block we process from
	// this point forward to the recovery batch.
	err = w.scanChain(startHeight, func(height int32,
		hash *chainhash.Hash, header *wire.BlockHeader) error {

		recoveryMgr.AddToBlockBatch(hash, height, header.Timestamp)

		// We'll checkpoint our current batch every 2K blocks, so we'll
		// need to start a new database transaction. If our current
		// batch is empty, then this will act as a NOP.
		if height%recoveryBatchSize == 0 {
			blockBatch := recoveryMgr.BlockBatch()
			err := w.recoverDefaultScopes(
				chainClient, tx, addrMgrNS, blockBatch,
				recoveryMgr.State(),
			)
			if err != nil {
				return err
			}

			// Clear the batch of all processed blocks.
			recoveryMgr.ResetBlockBatch()

			if err := tx.Commit(); err != nil {
				return err
			}

			log.Infof("Recovered addresses from blocks %d-%d",
				blockBatch[0].Height,
				blockBatch[len(blockBatch)-1].Height)

			tx, err = w.db.BeginReadWriteTx()
			if err != nil {
				return err
			}
			addrMgrNS = tx.ReadWriteBucket(waddrmgrNamespaceKey)
		}

		// Since the recovery in a way acts as a rescan, we'll update
		// the wallet's tip to point to the current block so that we
		// don't unnecessarily rescan the same block again later on.
		return w.Manager.SetSyncedTo(addrMgrNS, &waddrmgr.BlockStamp{
			Hash:      *hash,
			Height:    height,
			Timestamp: header.Timestamp,
		})
	})
	if err != nil {
		tx.Rollback()
		return err
	}

	// Now that we've reached the chain tip, we can process our final batch
	// with the remaining blocks if it did not reach its maximum size.
	blockBatch := recoveryMgr.BlockBatch()
	err = w.recoverDefaultScopes(
		chainClient, tx, addrMgrNS, blockBatch, recoveryMgr.State(),
	)
	if err != nil {
		tx.Rollback()
		return err
	}

	// With the recovery complete, we can persist our new state and exit.
	if err := tx.Commit(); err != nil {
		tx.Rollback()
		return err
	}

	if len(blockBatch) > 0 {
		log.Infof("Recovered addresses from blocks %d-%d", blockBatch[0].Height,
			blockBatch[len(blockBatch)-1].Height)
	}

	return nil
}
344002
func (r *Recover) Apply(next web.HandlerFunc) web.HandlerFunc {
	if r.StackSize == 0 {
		r.StackSize = 4 << 10 // 4 KB
	}

	pool := sync.Pool{
		New: func() interface{} {
			return make([]byte, r.StackSize)
		},
	}

	return func(ctx web.Context) error {
		defer func() {
			if e := recover(); e != nil {
				err := errors.Convert(e)
				if r.StackEnabled {
					stack := pool.Get().([]byte)
					length := runtime.Stack(stack, false)
					ctx.Logger().Errorf("PANIC: %s, stack: %s", err, stack[:length])
					pool.Put(stack)
				}
				ctx.Error(err)
			}
		}()

		return next(ctx)
	}
}
230845
func Recovery() macaron.Handler {
	return func(c *macaron.Context) {
		defer func() {
			if err := recover(); err != nil {
				stack := stack(3)

				panicLogger := log.Root
				// try to get request logger
				if ctx, ok := c.Data["ctx"]; ok {
					ctxTyped := ctx.(*m.ReqContext)
					panicLogger = ctxTyped.Logger
				}

				panicLogger.Error("Request error", "error", err, "stack", string(stack))

				c.Data["Title"] = "Server Error"
				c.Data["AppSubUrl"] = setting.AppSubUrl
				c.Data["Theme"] = setting.DefaultTheme

				if setting.Env == setting.DEV {
					if theErr, ok := err.(error); ok {
						c.Data["Title"] = theErr.Error()
					}

					c.Data["ErrorMsg"] = string(stack)
				}

				ctx, ok := c.Data["ctx"].(*m.ReqContext)

				if ok && ctx.IsApiRequest() {
					resp := make(map[string]interface{})
					resp["message"] = "Internal Server Error - Check the Grafana server logs for the detailed error message."

					if c.Data["ErrorMsg"] != nil {
						resp["error"] = fmt.Sprintf("%v - %v", c.Data["Title"], c.Data["ErrorMsg"])
					} else {
						resp["error"] = c.Data["Title"]
					}

					c.JSON(500, resp)
				} else {
					c.HTML(500, setting.ERR_TEMPLATE_NAME)
				}
			}
		}()

		c.Next()
	}
}
794437
func RecoveryHandlerCallback(tag string, opFunc func() error, cb func(interface{})) error {
	defer func() {
		if err := recover(); err != nil {
			cb(err)
			trace := make([]byte, 10000)
			count := runtime.Stack(trace, true)
			log.Printf("---------%s-Panic----------------:", strings.ToUpper(tag))
			log.Printf("Error: %+s", err)
			log.Printf("Stack of %d bytes: %+s\n", count, trace)
			log.Printf("---------%s--END-----------------:", strings.ToUpper(tag))
		}
	}()

	if err := opFunc(); err != nil {
		return err
	}

	return nil
}
736163
func NewRecovery() *Recovery {
	return &Recovery{
		Logger:     log.New(os.Stdout, "[negroni] ", 0),
		PrintStack: true,
		LogStack:   true,
		StackAll:   false,
		StackSize:  1024 * 8,
		Formatter:  &TextPanicFormatter{},
	}
}
540748
func panicRecover(f func(w dns.ResponseWriter, r *dns.Msg)) func(w dns.ResponseWriter, r *dns.Msg) {
	return func(w dns.ResponseWriter, r *dns.Msg) {
		defer func() {
			if rec := recover(); rec != nil {
				m := new(dns.Msg)
				m.SetRcode(r, 2)
				if err := w.WriteMsg(m); err != nil {
					logging.Error.Println(err)
				}
				logging.Error.Println(rec)
			}
		}()
		f(w, r)
	}
}
1134715
func Catch(cb func(p *Panic)) {
	if reason := recover(); reason != nil && cb != nil {
		stack := make([]byte, maxStackBufferSize)
		count := runtime.Stack(stack, true)
		cb(&Panic{
			Reason: reason,
			Stack:  string(stack[:count]),
		})
	}
}