Search in sources :

Example 41 with FieldError

use of org.springframework.validation.FieldError in project molgenis by molgenis.

the class ProblemExceptionResponseGeneratorTest method testCreateExceptionResponseInputInvalidFieldErrorCoded.

@Test
void testCreateExceptionResponseInputInvalidFieldErrorCoded() {
    String errorCode = "MYERR01";
    String errorMessage = "My error message";
    CodedRuntimeException wrappedException = mock(CodedRuntimeException.class);
    when(wrappedException.getErrorCode()).thenReturn(errorCode);
    when(wrappedException.getLocalizedMessage()).thenReturn(errorMessage);
    String field = "MyField";
    String value = "invalidValue";
    FieldError fieldError = new FieldError("MyObject", field, value, true, new String[] { errorCode }, new String[] { "arg0" }, "defaultMessage");
    fieldError.wrap(wrappedException);
    BindingResult bindingResult = new MapBindingResult(emptyMap(), "MyObject");
    bindingResult.addError(fieldError);
    BindException bindException = new BindException(bindingResult);
    HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    ResponseEntity<Problem> problemResponse = problemExceptionResponseGenerator.createExceptionResponse(bindException, httpStatus, false);
    assertEquals(httpStatus, problemResponse.getStatusCode());
    Problem problem = problemResponse.getBody();
    assertTrue(problem.getType().toString().endsWith("/input-invalid"));
    assertEquals(singletonList(builder().setErrorCode(errorCode).setField(field).setValue(value).setDetail(errorMessage).build()), problem.getErrors());
}
Also used : BindingResult(org.springframework.validation.BindingResult) MapBindingResult(org.springframework.validation.MapBindingResult) HttpStatus(org.springframework.http.HttpStatus) BindException(org.springframework.validation.BindException) FieldError(org.springframework.validation.FieldError) MapBindingResult(org.springframework.validation.MapBindingResult) CodedRuntimeException(org.molgenis.util.exception.CodedRuntimeException) Test(org.junit.jupiter.api.Test) AbstractMockitoTest(org.molgenis.test.AbstractMockitoTest)

Example 42 with FieldError

use of org.springframework.validation.FieldError in project molgenis by molgenis.

the class ErrorMessagesResponseGenerator method getErrorMessageResponse.

private static ErrorMessageResponse getErrorMessageResponse(Errors errors) {
    List<ErrorMessage> errorMessages = newArrayList();
    Locale locale = LocaleContextHolder.getLocale();
    MessageSource messageSource = MessageSourceHolder.getMessageSource();
    for (ObjectError objectError : errors.getGlobalErrors()) {
        String message = messageSource.getMessage("org.molgenis.web.exception.ObjectError", new Object[] { objectError.getObjectName(), objectError }, locale);
        errorMessages.add(new ErrorMessage(message, objectError.getCode()));
    }
    for (FieldError fieldError : errors.getFieldErrors()) {
        String message = messageSource.getMessage("org.molgenis.web.exception.FieldError", new Object[] { fieldError.getField(), fieldError.getObjectName(), fieldError }, locale);
        errorMessages.add(new ErrorMessage(message, fieldError.getCode()));
    }
    return new ErrorMessageResponse(errorMessages);
}
Also used : Locale(java.util.Locale) ObjectError(org.springframework.validation.ObjectError) MessageSource(org.springframework.context.MessageSource) FieldError(org.springframework.validation.FieldError) ErrorMessage(org.molgenis.web.ErrorMessageResponse.ErrorMessage) ErrorMessageResponse(org.molgenis.web.ErrorMessageResponse)

Example 43 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class ValidationErrorsMarshaller method marshalObject.

public void marshalObject(Object object, JSON json) throws ConverterException {
    Errors errors = (Errors) object;
    JSONWriter writer = json.getWriter();
    try {
        writer.object();
        writer.key("errors");
        writer.array();
        for (Object o : errors.getAllErrors()) {
            if (o instanceof FieldError) {
                FieldError fe = (FieldError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                json.property("field", fe.getField());
                json.property("rejected-value", fe.getRejectedValue());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            } else if (o instanceof ObjectError) {
                ObjectError fe = (ObjectError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            }
        }
        writer.endArray();
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + object.getClass().getName(), e);
    }
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) Locale(java.util.Locale) Errors(org.springframework.validation.Errors) ConverterException(org.grails.web.converters.exceptions.ConverterException) ObjectError(org.springframework.validation.ObjectError) FieldError(org.springframework.validation.FieldError) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Example 44 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class ValidationErrorsMarshaller method marshalObject.

public void marshalObject(Object object, XML xml) throws ConverterException {
    Errors errors = (Errors) object;
    try {
        for (Object o : errors.getAllErrors()) {
            if (o instanceof FieldError) {
                FieldError fe = (FieldError) o;
                xml.startNode("error");
                xml.attribute("object", fe.getObjectName());
                xml.attribute("field", fe.getField());
                xml.startNode("rejected-value").convertAnother(fe.getRejectedValue());
                xml.end();
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    xml.startNode("message").chars(applicationContext.getMessage(fe, locale)).end();
                } else {
                    String defaultMessage = fe.getDefaultMessage();
                    if (defaultMessage != null)
                        xml.startNode("message").chars(defaultMessage).end();
                }
                xml.end();
            }
        }
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + object.getClass().getName(), e);
    }
}
Also used : Locale(java.util.Locale) Errors(org.springframework.validation.Errors) ConverterException(org.grails.web.converters.exceptions.ConverterException) FieldError(org.springframework.validation.FieldError) BeansException(org.springframework.beans.BeansException) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Example 45 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Aggregations

FieldError (org.springframework.validation.FieldError)101 Test (org.junit.jupiter.api.Test)24 ObjectError (org.springframework.validation.ObjectError)20 BindingResult (org.springframework.validation.BindingResult)19 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)17 ApiOperation (io.swagger.annotations.ApiOperation)13 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)12 Errors (org.springframework.validation.Errors)11 ArrayList (java.util.ArrayList)10 BindException (org.springframework.validation.BindException)7 Locale (java.util.Locale)6 CustomResult (com.megagao.production.ssm.domain.customize.CustomResult)5 Test (org.junit.Test)5 MapBindingResult (org.springframework.validation.MapBindingResult)5 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)5 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)5 JsonResult (com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult)4 Method (java.lang.reflect.Method)4 HashMap (java.util.HashMap)4 ErrorMessage (org.springframework.cloud.servicebroker.model.error.ErrorMessage)4