gitea源码

errpage.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package common
  4. import (
  5. "fmt"
  6. "net/http"
  7. user_model "code.gitea.io/gitea/models/user"
  8. "code.gitea.io/gitea/modules/httpcache"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/templates"
  12. "code.gitea.io/gitea/modules/web/middleware"
  13. "code.gitea.io/gitea/modules/web/routing"
  14. "code.gitea.io/gitea/services/context"
  15. )
  16. const tplStatus500 templates.TplName = "status/500"
  17. // RenderPanicErrorPage renders a 500 page, and it never panics
  18. func RenderPanicErrorPage(w http.ResponseWriter, req *http.Request, err any) {
  19. combinedErr := fmt.Sprintf("%v\n%s", err, log.Stack(2))
  20. log.Error("PANIC: %s", combinedErr)
  21. defer func() {
  22. if err := recover(); err != nil {
  23. log.Error("Panic occurs again when rendering error page: %v. Stack:\n%s", err, log.Stack(2))
  24. }
  25. }()
  26. routing.UpdatePanicError(req.Context(), err)
  27. httpcache.SetCacheControlInHeader(w.Header(), &httpcache.CacheControlOptions{NoTransform: true})
  28. w.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  29. tmplCtx := context.TemplateContext{}
  30. tmplCtx["Locale"] = middleware.Locale(w, req)
  31. ctxData := middleware.GetContextData(req.Context())
  32. // This recovery handler could be called without Gitea's web context, so we shouldn't touch that context too much.
  33. // Otherwise, the 500-page may cause new panics, eg: cache.GetContextWithData, it makes the developer&users couldn't find the original panic.
  34. user, _ := ctxData[middleware.ContextDataKeySignedUser].(*user_model.User)
  35. if !setting.IsProd || (user != nil && user.IsAdmin) {
  36. ctxData["ErrorMsg"] = "PANIC: " + combinedErr
  37. }
  38. err = templates.HTMLRenderer().HTML(w, http.StatusInternalServerError, tplStatus500, ctxData, tmplCtx)
  39. if err != nil {
  40. log.Error("Error occurs again when rendering error page: %v", err)
  41. w.WriteHeader(http.StatusInternalServerError)
  42. _, _ = w.Write([]byte("Internal server error, please collect error logs and report to Gitea issue tracker"))
  43. }
  44. }