package br.com.alura.forum.controller.form;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TopicoForm {
@NotNull
@NotEmpty
private String titulo;
@NotNull
@NotEmpty
private String mensagem;
@NotNull
@NotEmpty
private String nomeCurso;
public Topico converter(CursoRepository cursoRepository) {
Curso curso = cursoRepository.findByNome(nomeCurso);
return new Topico(titulo, mensagem, curso);
}
}
package br.com.alura.forum.controller;
@RestController
@RequestMapping("/topicos")
public class TopicosController {
@Autowired
private TopicoRepository topicoRepository;
@Autowired
private CursoRepository cursoRepository;
@GetMapping
public List<TopicoDto> lista(String nomeCurso) {
if (nomeCurso == null) {
List<Topico> topicos = topicoRepository.findAll();
return TopicoDto.converter(topicos);
} else {
List<Topico> topicos = topicoRepository.carregarPorNomeDoCurso(nomeCurso);
return TopicoDto.converter(topicos);
}
}
@PostMapping
public ResponseEntity<TopicoDto> cadastrar(@Valid @RequestBody TopicoForm form, UriComponentsBuilder uriBuilder) {
Topico topico = form.converter(cursoRepository);
topicoRepository.save(topico);
URI uri = uriBuilder.path("/topicos/{id}").buildAndExpand(topico.getId()).toUri();
return ResponseEntity.created(uri).body(new TopicoDto(topico));
}
}
@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;
}
}
Mensagem gerada no console:
2019-12-30 17:03:03.911 WARN 280 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<br.com.alura.forum.controller.dto.TopicoDto> br.com.alura.forum.controller.TopicosController.cadastrar(br.com.alura.forum.controller.form.TopicoForm,org.springframework.web.util.UriComponentsBuilder)]