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

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