gpt4 book ai didi

grails - Grails 'Cannot issue a redirect'问题

转载 作者:行者123 更新时间:2023-12-02 15:10:54 24 4
gpt4 key购买 nike

正在发生以下问题:

def someAction() {
...
if (someCondition)
redirect action: 'index'
return
}

if (someOtherCondition)
redirect action: 'index'
return
}

...

redirect action: 'success'
}

这很完美。但是,一旦我将其包装在交易中:
def someAction() {
MyDomainClass.withTransaction { status ->

if (someCondition)
status.setRollbackOnly()
redirect action: 'index'
return
}

if (someOtherCondition)
status.setRollbackOnly()
redirect action: 'index'
return
}

...

}

redirect action: 'success'
}

这将引发异常:

Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.. Stacktrace follows: Message: Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.



奇怪的是,我在另一段代码中做的完全一样,而且效果很好。唯一的区别是我链接而不是重定向。我在上面的代码中尝试了链接,但是仍然抛出异常。

最佳答案

return来自:

MyDomainClass.withTransaction { status ->

if (someCondition)
status.setRollbackOnly()
redirect action: 'index'
return // <-- !!! this one !!!
}
}

从封闭块,而不是从行动返回您。因此,它调用 redirect action: 'index',从闭包退出,然后在执行块之后执行另一个重定向:
redirect action: 'success'

最后一个导致此异常。

解决方法是,您可以记住重定向状态并检查最后一步,例如:
boolean redirected = false
MyDomainClass.withTransaction { status ->

if (someCondition)
status.setRollbackOnly()
redirected = true
redirect action: 'index'
return
}
}
if (!redirected) {
redirect action: 'success'
}

或只是检查响应是否尚未提交(但这种方式似乎有点不可靠):
if (!response.commited) {
redirect action: 'success'
}

关于grails - Grails 'Cannot issue a redirect'问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com