handleCustomException
方法?我在一个简单的项目中重新创建了这个问题,看看它是否是我意外完成的疯狂事件,但它似乎是默认的grails行为。
我有一个包含以下内容的控制器:
package simpletestproject
import simpleTestProject.exceptions.CustomException
class ExceptionTestController {
SimpleService simpleService
def index() {
println("index called")
someMethod()
println("someMethod has been called")
}
def viaService() {
println("viaService called")
simpleService.serviceMethod()
println("simpleService.someMethod has been called")
}
def someMethod() throws CustomException{
println("foo... someMethod")
throw new CustomException("some Response with an errocode", "You have seen an exception from the CONTROLLER")
println("this should not be seen")
}
def handleCustomException(final CustomException exception){
println("EXCEPTION CAUGHT - ${ exception.getErroneousResponse() } - ${ exception.getMessage() }")
render("Exception Handled")
}
}
以及包含以下内容的单一服务:
package simpletestproject
import grails.transaction.Transactional
import simpleTestProject.exceptions.CustomException
@Transactional
class SimpleService {
def serviceMethod() {
println("serviceMethod")
throw new CustomException("some Response with an errocode", "You have seen an exception from the SERVICE")
println("serviceMethod - this should not be seen")
}
}
如果我导航到http://localhost:8080/simpleTestProject/ExceptionTest,我会看到以下内容:
index called
foo... someMethod
EXCEPTION CAUGHT - some Response with an errocode - You have seen an exception from the CONTROLLER
someMethod has been called
如果我导航到http://localhost:8080/simpleTestProject/ExceptionTest/viaService,我会看到以下内容:
viaService called
serviceMethod
EXCEPTION CAUGHT - some Response with an errocode - You have seen an exception from the SERVICE
仅供参考 - 我的CustomException如下:
package simpleTestProject.exceptions
class CustomException extends RuntimeException {
private Object erroneousResponse
public CustomException(Object erroneousResponse, String message) {
super(message)
if(erroneousResponse == null) {
this.erroneousResponse = "NULL Response"
}
else {
this.erroneousResponse = erroneousResponse
}
}
public Object getErroneousResponse() {
return this.erroneousResponse
}
}
提前感谢您的帮助!
修改
我还尝试直接致电someMethod
(http://localhost:8080/simpleTestProject/ExceptionTest/someMethod)并看到以下输出:
foo... someMethod
EXCEPTION CAUGHT - some Response with an errocode - You have seen an exception from the CONTROLLER
这符合服务的行为,以及我期望看到的内容。
答案 0 :(得分:2)
您不应该只在Grails控制器中调用另一个操作。 (someMethod()是一个动作,因为它是控制器中的非私有方法。)
如果需要,您可以重定向到它,或者包含它。或者你可以把它变成一个私有方法(然后它不再是一个动作,你可以按照你现在的方式继续调用它),或者将它移动到一个服务。但是通常不会像你想要的那样从另一个明确地调用一个动作。
基本解释是默认的grails控制器为操作添加了特殊处理。根据您使用的grails版本,它确实有所不同,但基本上它们将以某种常见的方式处理它们的params和任何异常。