2017-04-19 28 views
0

更新域實例時,我需要在允許更新之前檢查一些數據。 我在beforUpdate方法中創建了它,它可以防止更新,但在Flash消息中,您可以閱讀「域68已更新!」這不是我想要展示給用戶的。Grails,如果我發現錯誤,該如何從域中發送消息(鍵入flash)?

更新前是這樣的:

def beforeUpdate() { 
    def oldVolume = getPersistentValue('volumeInStock') 
    if (oldVolume != volumeInStock && oldVolume!=volumeInitial){ 
     throw new ValidationException("Changing InStock not allowed after offer/sold or planed volumes added!",this) 
    } 
} 

我在想拋出一個異常,而是不敢看,因爲我想的那麼簡單。當我嘗試上面的代碼時說它有這樣的方法。我找不到任何示例或說明我應該怎樣打電話。 所以主要的問題是如何告知用戶這個問題? 是否使用異常的Wright方式,那麼我需要一些幫助如何做到這一點,否則我還能做什麼? :(

+0

嘗試更改拋出新的ValidationException(「更改InStock不允許在提供/出售或計劃卷添加!」,this)'this.errors.rejectValue('volumeInStock',「failedVolume.error')' – Vahid

+0

不會阻止grails保存實例,但如果我使用「return false」,那就只需要停止它就可以保存。但是當然,我沒有收到消息 - 它仍然表示已更新。 – larand

回答

0

我傾向於對我的控制器使用通用的異常處理機制,如下面這種適用於大多數情況的方法,如果您需要做其他工作而不是將消息呈現給屏幕,則可能無法爲您工作

trait ControllerExceptionHandler { 

    def handleException(Exception e) { 
     def msg = e.message ?: e?.cause?.message 
     flash.fail = msg 
     log.info msg 
     return 
    } 
} 

然後你的控制器實現這一特質:

class MyController implements ControllerExceptionHandler { 
    def save() { 
     // do something that might throw an exception, if it does the ControllerExceptionHandler will deal with it 
     // it worked 
     flash.message = message(code: 'default.success.message') 
    } 
} 

在你GSPS:

<g:render template="/templates/alerts"/> 

視圖/模板/ _alerts.gsp

<g:if test="${flash.message}"> 
    <g:render template="/templates/message" model="[type: 'info', message: flash.message]" /> 
</g:if> 
<g:if test="${flash.fail}"> 
    <g:render template="/templates/message" model="[type: 'danger', message: flash.fail]" /> 
</g:if> 

視圖/模板/ _message.gsp

<div class="alert alert-${type} alert-dismissible" role="alert"> 
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
    ${message} 
</div> 

上面利用自舉造型。

+0

好的,但那就是第2步。第1步是「我應該如何在」beforeUpdate「方法中編寫」throw xxxxException('My error message')「? – larand

+0

TBH我沒有在域中使用beforeXXXX等方法,我通常在我的服務中進行域非約束驗證,我認爲如果您更改爲例如拋出新的UnsupportedOperationException(「改變InStock不允許在提供/出售或計劃卷添加後!」)這將使用beforeXXXX上面的工作,我猜測ValidationException被Grails捕獲&不傳播回控制器。 –

0

但是爲什麼你要避免標準的grails驗證mechanism

只要定義約束條件,validate()save(),如果hasErrors()將錯誤置於flash

投擲異常可能會破壞您的交易(如果您保存在交易服務中,建議這樣做)。