문제

In Grails,

When an specific 'unique' constraint is violated, I want to set the message of the Exception that rises.

Is that possible?

도움이 되었습니까?

해결책

The message code to use for each constraint is listed in the reference page for that constraint, e.g. http://grails.org/doc/latest/ref/Constraints/unique.html. From that it looks like the code you need is

com.project.ModelName.fieldName.unique=blah 

You need to replace com.project.ModelName.fileName with your appropriate value

Thanks to http://grails.1312388.n4.nabble.com/Custom-error-message-in-message-properties-td3335696.html

다른 팁

Just to update on given answer, the above and even the documentation seems to suggest :

This constraint influences schema generation.

Error Code: className.propertyName.unique

But this wasn't true in the case of my app, maybe things have changed in grails 3. I tried a tiresome variation and to no success still had the default values returned.

The solution for anyone else facing this is really quite easy.

Locate the default entry that returns the response:

In my case I had two entries:

##default.not.unique.message=Property [{0}] of class [{1}] with value [{2}] must be unique
##default.not.unique.message={0} must be unique

Commented them both out by adding hashes at the start of the line and attempted to save record again. This time on my web interface I saw the actual field name rather than the default grails message.

unique.com.xxx.users.PhotosBean.imageSHa

and I added the entry for this key in messages.properties to find all is working well.

Notice also it was hanging off the subclass rather than actual class, maybe in my case it was way over complicated.

The trick in these circumstances is to comment out the default entries returning values and then re-enable when actual constraint returned.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top