You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

errpage.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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/base"
  9. "code.gitea.io/gitea/modules/httpcache"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/templates"
  13. "code.gitea.io/gitea/modules/web/middleware"
  14. "code.gitea.io/gitea/modules/web/routing"
  15. )
  16. const tplStatus500 base.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(), 0, "no-transform")
  28. w.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  29. data := middleware.GetContextData(req.Context())
  30. if data["locale"] == nil {
  31. data = middleware.CommonTemplateContextData()
  32. data["locale"] = middleware.Locale(w, req)
  33. }
  34. // This recovery handler could be called without Gitea's web context, so we shouldn't touch that context too much.
  35. // Otherwise, the 500-page may cause new panics, eg: cache.GetContextWithData, it makes the developer&users couldn't find the original panic.
  36. user, _ := data[middleware.ContextDataKeySignedUser].(*user_model.User)
  37. if !setting.IsProd || (user != nil && user.IsAdmin) {
  38. data["ErrorMsg"] = "PANIC: " + combinedErr
  39. }
  40. err = templates.HTMLRenderer().HTML(w, http.StatusInternalServerError, string(tplStatus500), data)
  41. if err != nil {
  42. log.Error("Error occurs again when rendering error page: %v", err)
  43. w.WriteHeader(http.StatusInternalServerError)
  44. _, _ = w.Write([]byte("Internal server error, please collect error logs and report to Gitea issue tracker"))
  45. }
  46. }