github.com/companieshouse/insolvency-api@v0.0.0-20231024103413-440c973d9e9b/handlers/recovery.go (about)

     1  package handlers
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"runtime/debug"
     7  
     8  	"github.com/companieshouse/chs.go/log"
     9  	"github.com/companieshouse/insolvency-api/models"
    10  	"github.com/companieshouse/insolvency-api/utils"
    11  )
    12  
    13  // RecoveryHandler is a handler wrapper that catches runtime panics and returns a 500 Internal Server Error
    14  func RecoveryHandler(h http.Handler) http.Handler {
    15  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    16  
    17  		defer func() {
    18  			if err := recover(); err != nil {
    19  				log.ErrorR(req, fmt.Errorf("runtime error [%s]: %s", err, debug.Stack()))
    20  				m := models.NewMessageResponse("there was a problem handling your request")
    21  				utils.WriteJSONWithStatus(w, req, m, http.StatusInternalServerError)
    22  			}
    23  		}()
    24  		h.ServeHTTP(w, req)
    25  	})
    26  }