I want to throw an exception when I parse the received object to a DTO and while parsing if any of the fields in DTO that I have marked as required has null values then I want to throw an exception with 400 response.
I have a controller like this,
public class StandardController(@RequestBody Object body) { ModelMapper modelMapper = new ModelMapper(); try { CustomDTO customDto = modelMapper.map(body, CustomDTO.class); } catch (Exception e) { //throw exception with a message required properties are missing with 400 response` } }
I have marked a few properties in my CustomDTO as required = true
with JsonProperty
. But when I test the controller, its not throwing an exception.
Any idea how I can implement this scenario?
Advertisement
Answer
You need to receive CustomDto directly from the user. Because DTO is meant for transfer. If you receive custom dto from user then you can add validation on the object.
Just an example
@Data public class ClassDto { private Long classId; @NotNull @Size(max = 200) private String className; private Double classAdmissionFee; }
Look at the @NotNull and @Size annotation. They comes under javax validation.
Now once after your DTO is fully configured. You need to do this:
public class StandardController(@Valid @RequestBody CustomDTO customDto) { }
Notice the @Valid annotation. While any of the DTO constraints fails spring will throw a MethodArgumentNotValidException. So you need to handle the exception via @ControllerAdvice or extending ResponseEntityExceptionHandler.
Here is a nice article link for your case: https://www.javaguides.net/2021/04/spring-boot-dto-validation-example.html