Grails从ErrorController渲染404,403,500个错误作为JSON

时间:2015-07-22 18:29:12

标签: json grails error-handling http-status-code-404

运行Grails 2.4.3,我创建了一个ErrorController,其中包含处理403,404和500错误的方法。我有3个方法的GSP,它们渲染得很好,但如果请求使用' .json'我还想让它们返回JSON响应。延期。我的代码如下所示,只返回gsp版本而不管请求类型,因此,即使是使用' .json'扩展正在渲染gsp。如何使JSON版本正常工作?

UrlMappings:

class UrlMappings {
    static mappings = {
        "/" (controller: "home", action: "index")
        ...

        "403" (controller: "error", action: "forbidden")
        "404" (controller: "error", action: "notFound")
        "500" (controller: "error", action: "index")
    }
}

ErrorController:

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') }
        }
    }
}

0 个答案:

没有答案