gpt4 book ai didi

validation - Grails,如果我发现错误,如何从域发送消息(类型 flash)?

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

更新域实例时,我需要在允许更新之前检查一些数据。
我在 beforUpdate 方法中创建了它,它阻止了更新,但在 flash 消息中您可以阅读“域 68 已更新!”这不是我想向用户展示的。

beforeUpdate 看起来像这样:

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)
}
}

我正在考虑抛出异常,但这看起来并不像我想象的那么容易。当我尝试上面的代码时,它说有这样的方法。而且我找不到任何示例或说明我应该如何调用电话。
所以主要问题是我如何通知用户这个问题?
这是使用异常的正确方式,那么我需要一些帮助如何做到这一点,否则我还能做什么? :(

最佳答案

我倾向于为我的 Controller 使用通用异常处理机制,如下所示,它适用于大多数场景,如果您需要做其他事情而不是将消息呈现到屏幕上,这可能对您不起作用。

trait ControllerExceptionHandler {

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

然后你的 Controller 实现这个特性:
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"/>

View /模板/_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>

View /模板/_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>

上面使用了引导样式。

关于validation - Grails,如果我发现错误,如何从域发送消息(类型 flash)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43491915/

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