go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/middleware/panic.go (about)

     1  // Copyright 2021 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package middleware
    16  
    17  import (
    18  	"net/http"
    19  
    20  	"go.chromium.org/luci/common/logging"
    21  	"go.chromium.org/luci/common/runtime/paniccatcher"
    22  
    23  	"go.chromium.org/luci/server/router"
    24  )
    25  
    26  // WithPanicCatcher is a middleware that catches panics, dumps stack trace to
    27  // logging and returns HTTP 500.
    28  func WithPanicCatcher(c *router.Context, next router.Handler) {
    29  	ctx := c.Request.Context()
    30  	w := c.Writer
    31  	uri := c.Request.RequestURI
    32  	defer paniccatcher.Catch(func(p *paniccatcher.Panic) {
    33  		// Log the reason before the stack in case appengine cuts entire log
    34  		// message due to size limitations.
    35  		logging.Fields{
    36  			"panic.error": p.Reason,
    37  		}.Errorf(ctx, "Caught panic during handling of %q: %s\n%s", uri, p.Reason, p.Stack)
    38  
    39  		// Note: it may be too late to send HTTP 500 if `next` already sent
    40  		// headers. But there's nothing else we can do at this point anyway.
    41  		http.Error(w, "Internal Server Error. See logs.", http.StatusInternalServerError)
    42  	})
    43  	next(c)
    44  }