package br.com.alura.forum.config.validacao;
import java.util.ArrayList; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice public class ErroDeValidacaoHandler { @Autowired private MessageSource messageSource;
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public List<ErroDeFormularioDto> handle(MethodArgumentNotValidException exception) {
List<ErroDeFormularioDto> dto = new ArrayList<>();
List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
fieldErrors.forEach(e -> {
String mensagem = messageSource.getMessage(e, localeContextHolder.getLocaLe());
ErroDeFormularioDto erro = new ErroDeFormularioDto(e.getField(), mensagem);
dto.add(erro);
});
return dto;
}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'erroDeValidacaoHandler' defined in file [C:\Users\carlo\Documents\forum\target\classes\br\com\alura\forum\config\validacao\ErroDeValidacaoHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [br.com.alura.forum.config.validacao.ErroDeValidacaoHandler]: Constructor threw exception; nested exception is java.lang.Error: Unresolved compilation problem: localeContextHolder cannot be resolved