Grails从ErrorController将404403500个错误呈现为JSON
运行Grails2.4.3,我创建了一个ErrorController,其中包含处理403、404和500个错误的方法。我有3个方法的GSP,它们呈现良好,但是如果请求使用“.JSON”扩展名,我还希望它们返回JSON响应。下面编写的代码只返回gsp版本,而不考虑请求类型,因此,即使扩展名为“.json”的请求也会呈现gsp。如何让JSON版本正常工作 URL映射:Grails从ErrorController将404403500个错误呈现为JSON,json,grails,error-handling,http-status-code-404,Json,Grails,Error Handling,Http Status Code 404,运行Grails2.4.3,我创建了一个ErrorController,其中包含处理403、404和500个错误的方法。我有3个方法的GSP,它们呈现良好,但是如果请求使用“.JSON”扩展名,我还希望它们返回JSON响应。下面编写的代码只返回gsp版本,而不考虑请求类型,因此,即使扩展名为“.json”的请求也会呈现gsp。如何让JSON版本正常工作 URL映射: class UrlMappings { static mappings = { "/" (controll
class UrlMappings {
static mappings = {
"/" (controller: "home", action: "index")
...
"403" (controller: "error", action: "forbidden")
"404" (controller: "error", action: "notFound")
"500" (controller: "error", action: "index")
}
}
错误控制器:
class ErrorController {
def forbidden() {
withFormat {
json {
render(contentType: "text/json") { response ERROR: [code: 403, msg: "Access Denied."] }
}
'*' { render(view: 'forbidden') }
}
}
def notFound() {
withFormat {
json {
render(contentType: "text/json") { response ERROR: [code: 404, msg: "Page not found."] }
}
'*' { render(view: 'notFound') }
}
}
def index() {
withFormat {
json {
render(contentType: "text/json") { response ERROR: [code: 500, msg: "Internal Server Error."] }
}
'*' { render(view: 'internalServer') }
}
}
}
看起来您必须在home controller中的
响应之后抛出异常。sendError(403)
,然后错误处理可以使用with format
。这看起来很奇怪。更好的方法是处理错误和异常,如果可行的话。我很困惑。您说我需要“在响应后抛出异常。主控制器中的sendError(403)”您可以包括和示例吗?然后你说“这看起来很奇怪”-你是指“在主控制器中的response.senderro(403)之后抛出异常”还是我的代码?另外,我不明白您称之为“更好的方式”的模式如何适合我的代码。你能举个例子吗?为什么它只提供普惠制版本?我的错。我的观点是,只有在sendError()
之后抛出异常时,它才会像您编写的那样工作。我确实有一个例子,当我看到这个问题时,我正在尝试,但我无法找到(