How to integrate validationexception from entitylistener in GUI

I have a entity listener for performing validation as described in Validation in Java applications – Jmix

When validation fails I throw a javax.validation.ValidationException, also tried with ConstraintViolationExceptoin.

I expected/hoped this exception to be picked up by the GUI and shown in a nice validation notification in the way it works for declarative validation.

image

instead I get a generic exception dialog image

How can I wire this in, preferably without having to implement commit event listeners in all the screens.

bump

anyone?

You can create an Exception Handler for the whole UI part as described in the documentation

Something like this.

Entity listener with validation in core module:

@Component("sessionplanner_SessionListener")
public class SessionEntityListener implements BeforeInsertEntityListener<Session> {

    @Override
    public void onBeforeInsert(Session entity, EntityManager entityManager) {
        if (entity.getStartDate().isBefore(LocalDateTime.now())) {
            throw new CustomValidationException("Cannot plan session!");
        }
    }
}

Exception handler in web module:


@Component(ValidationExeptionHandler.NAME)
public class ValidationExeptionHandler extends AbstractUiExceptionHandler {
    public static final String NAME = "sessionplanner_ValidationExeptionHandler";

    public ValidationExeptionHandler() {
        super(CustomValidationException.class.getName());
    }

    @Override
    protected void doHandle(String className, String message, @Nullable Throwable throwable, UiContext context) {
        context.getNotifications().create(Notifications.NotificationType.ERROR)
                .withCaption("Error")
                .withDescription(message)
                .show();
    }
}
1 Like