14

当获得 HTTP 状态码 500 时,我想根据运行环境显示 2 个不同的页面。

在开发模式下,我想显示一个 stackStrace 页面(就像默认的 Grails 500 错误页面),在生产模式下,我想显示一个正式的“内部错误”页面。

有可能吗?我该怎么做?

4

2 回答 2

20

您可以在其中进行特定于环境的映射UrlMappings.groovy

grails.util.GrailsUtil救援

它不漂亮,但我认为它会解决你的问题

例如

import grails.util.GrailsUtil

class UrlMappings {
    static mappings = {


        if(GrailsUtil.getEnvironment() == "development") {

             "/$controller/$action?/$id?"{
                constraints {
                    // apply constraints here
                }
            }

            "/"(view:"/devIndex")
            "500"(view:'/error')
        }

        if(GrailsUtil.getEnvironment() == "test") {
            "/$controller/$action?/$id?"{
                constraints {
                    // apply constraints here
                }
            }

            "/"(view:"/testIndex")
            "500"(view:'/error')

        }



        if(GrailsUtil.getEnvironment() == "production") {
            "/$controller/$action?/$id?"{
                constraints {
                    // apply constraints here
                }
            }

            "/"(view:"/prodIndex")
            "500"(view:'/error')

        }
    }
}
于 2010-05-27T21:24:32.773 回答
14

可能有一种更简洁的方法可以做到这一点,但我已经将错误代码映射到控制器并在那里处理逻辑:

class UrlMappings {

   static mappings = {

      "/$controller/$action?/$id?" { constraints {} }

      "/"(view:"/index")

      "403"(controller: "errors", action: "accessDenied")
      "404"(controller: "errors", action: "notFound")
      "405"(controller: "errors", action: "notAllowed")
      "500"(view: '/error')
   }
}

然后创建对应的控制器(grails-app/conf/controllers/ErrorsController.groovy):

import grails.util.Environment

class ErrorsController extends AbstractController {

   def accessDenied = {}

   def notFound = {}

   def notAllowed = {}

   def serverError = {
      if (Environment.current == Environment.DEVELOPMENT) {
         render view: '/error'
      }
      else {
         render view: '/errorProd'
      }
   }
}

您需要在 grails-app/views/errors(accessDenied.gsp、notFound.gsp 等)以及新的 grails-app/views/errorProd.gsp 中创建相应的 GSP。通过为所有错误代码路由到控制器方法,您可以更轻松地在将来向其他错误代码处理程序添加逻辑。

于 2010-05-27T20:51:22.013 回答