I am trying to write a Grails 3 interceptor that should check if certain variables are present in the HTTP Headers. If they are not present i would like to render a specific json view but it seems that the render method is not availble in the before() method.
boolean before() {
String header = request.getHeader("Authorization")
if(!header) {
BaseException exception = new BadRequestException("test")
render view: "/genericErrorReponse", model: [e: exception]
return false
}
Is there a better way to achieve the desired result?
I am getting the following error when trying to render the JSON view.
No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined.
No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined: expected single matching bean but found 4: groovyMarkupViewResolver,jsonViewResolver,beanNameViewResolver,mvcViewResolver. Stacktrace follows:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined: expected single matching bean but found 4: groovyMarkupViewResolver,jsonViewResolver,beanNameViewResolver,mvcViewResolver
at grails.artefact.Interceptor$Trait$Helper.render(Interceptor.groovy:254) ~[grails-plugin-interceptors-3.1.1.jar:3.1.1]
at device.registration.RegistrationInterceptor.before(RegistrationInterceptor.groovy:13) ~[main/:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_66]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Interceptor Code
class RegistrationInterceptor {
boolean before() {
String header = request.getHeader("Authorization")
if(!header) {
render view: "/genericErrorResponse", model: [e: new BadRequestException()]
}
false
}
boolean after() { true }
void afterView() {
// no-op
}
}
JSON View [/genericErrorResponse]
model {
BaseException e
}
response.status e.status
json {
message e.message
error e.error
status e.status
timestamp e.timestamp
}
It seemed that it actually was a bug inside Grails 3. Please see https://github.com/grails/grails-core/issues/9688