- 爲什麼我在控制器中拋出和異常是錯誤的?
- 爲什麼在控制器中拋出異常暫停執行,但在服務中拋出異常呢?
- 如果可能的話,我錯過了什麼來停止執行,並且在從控制器中拋出時只執行
handleCustomException
方法?
我在一個簡單的項目中重新創建了這個問題,看看它是不是我曾經意外完成的事情,但它似乎是默認的grails行爲。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
這會將與服務的行爲,我期待什麼查看。
也許這個特殊處理的鏈接會很好嗎?這不是我在文檔中看到的東西。接受作爲一種私人方法爲我工作。謝謝 –