There is an annotation that should ideally throw an exception if the entity by id is not found for different controllers. Annotation:
@Target({ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CheckExistHandler.class)
public @interface CheckExist {
Class<?> entityClass();
String message() default "Entity with specified id does not exist!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
validator sketches:
@Component
public class CheckExistHandler implements ConstraintValidator<CheckExist, Long> {
@PersistenceContext
private EntityManager entityManager;
@Override
public boolean isValid(Long value, ConstraintValidatorContext context) {
if (value != 0 && entityManager.find(Topic.class, value) != null) {
return true;
} else {
return false;
}
}
}
Method for tests from one controller:
@GetMapping("/{topicId}")
public ResponseEntity<TopicDto> getTopicById(@CheckExist(entityClass = Topic.class) @PathVariable("topicId") Long topicId) {
if (!topicService.isExistByKey(topicId)) {
throw new NotFoundException("topic not found");
}
return new ResponseEntity<>(topicMapper.toDto(topicService.getByKey(topicId)), HttpStatus.OK);
}
In this regard, questions:
- How to isolate a class from an annotation in a validator using reflection in order to correctly use the EntityManager?
- How to throw an exception without getting 500?