Я все еще изучаю JHipster, поэтому сегодня я подумал о том, чтобы самостоятельно выполнить несколько упражнений по проверке и попытаться отправить осмысленные сообщения об ошибках на мой интерфейс.
Вот что я пробовал
В моем контроллере у меня есть следующее:
/**
* POST /lessons : Create a new lesson of 45 min.
*
* if lesson is of type creno or circulation the car is mandatory
*
* @param lessonDTO the lessonDTO to create
* @return the ResponseEntity with status 201 (Created) and with body the new lessonDTO, or with status 400 (Bad Request) if the lesson has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/lessons")
public ResponseEntity<LessonDTO> createLesson(@Valid @RequestBody LessonDTO lessonDTO) throws URISyntaxException {
log.debug("REST request to save Lesson : {}", lessonDTO);
if (lessonDTO.getId() != null) {
throw new BadRequestAlertException("A new lesson cannot already have an ID", ENTITY_NAME, "idexists");
}
if (!lessonService.checkLessonTime(lessonDTO)){
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME,"EK_L_C01", "erreur de requete dupliquer")).build();
}
LessonDTO result = lessonService.save(lessonDTO);
return ResponseEntity.created(new URI("/api/lessons/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
как вы видите, если проверка времени урока не удалась, я должен отправить неверный ответ на запрос с кодом ошибки EK_L_C01, тогда мой следующий шаг - внести небольшое изменение во внешний интерфейс, где я должен это сделать.
save() {
this.isSaving = true;
this.lesson.dateLesson = this.dateLesson != null ? moment(this.dateLesson, DATE_TIME_FORMAT) : null;
if (this.lesson.id !== undefined) {
this.subscribeToSaveResponse(this.lessonService.update(this.lesson));
} else {
this.subscribeToSaveResponse(this.lessonService.create(this.lesson));
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<ILesson>>) {
result.subscribe((res: HttpResponse<ILesson>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError(res.message));
}
protected onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
protected onSaveError(errorMessage: string) {
this.isSaving = false;
this.onError(errorMessage);
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
затем я добавил перевод кода в свой глобальный.json, как показано ниже.
"error": {
"internalServerError": "Erreur interne du serveur",
"server.not.reachable": "Serveur inaccessible",
"url.not.found": "Non trouvé",
"NotNull": "Le champ {{fieldName}} ne peut pas être vide !",
"Size": "Le champ {{fieldName}} ne respecte pas les critères minimum et maximum !",
"userexists": "Login déjà utilisé !",
"emailexists": "Email déjà utilisé !",
"idexists": "Une nouvelle entité {{entityName}} ne peut pas avoir d'ID !",
"idnull": "Invalid ID",
"EK_L_C01": "Impossible de reserver une lesson : nombre maximal de lesson attein {{dateLesson}} "
},
У меня отображается мое сообщение, но нет значения даты.
Как вы видите, я хочу указать дату, используемую в качестве переменной сообщения об ошибке, но я не знаю, как это сделать, поэтому как я могу добавить это значение даты в свое сообщение об ошибке?





Привет. После целого дня плавания кода я обнаружил, что Jhipster уже сделал механизм обработки ошибок в пакете web/rest/errors, он полон Throwable, что кажется удобным, для моего случая это было CustomParameterizedException
То, что я сделал, было просто
Первый урок создания моего контроллера стал таким:
@PostMapping("/lessons")
public ResponseEntity<LessonDTO> createLesson(@Valid @RequestBody LessonDTO lessonDTO) throws URISyntaxException {
log.debug("REST request to save Lesson : {}", lessonDTO);
if (lessonDTO.getId() != null) {
throw new BadRequestAlertException("A new lesson cannot already have an ID", ENTITY_NAME, "idexists");
}
if (!lessonService.checkLessonTime(lessonDTO)){
throw new CustomParameterizedException("error.EK_L_C01", lessonDTO.getDateLesson().toString());
}
LessonDTO result = lessonService.save(lessonDTO);
return ResponseEntity.created(new URI("/api/lessons/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
затем мой global.json был обновлен следующим образом
"error": {
"internalServerError": "Erreur interne du serveur",
"server.not.reachable": "Serveur inaccessible",
"url.not.found": "Non trouvé",
"NotNull": "Le champ {{fieldName}} ne peut pas être vide !",
"Size": "Le champ {{fieldName}} ne respecte pas les critères minimum et maximum !",
"userexists": "Login déjà utilisé !",
"emailexists": "Email déjà utilisé !",
"idexists": "Une nouvelle entité {{entityName}} ne peut pas avoir d'ID !",
"idnull": "Invalid ID",
"EK_L_C01": "Impossible de reserver une lesson : nombre maximal de lesson attein pour la date {{param0}} "
},
Таким образом, при сбое checkLessonTime я получаю желаемое сообщение об ошибке с параметрами
Спасибо за интерес, желаю, чтобы это помогло другим новичкам в jhipster.
Для более подробной информации читайте код класса CustomParameterizedException.
Это полностью изменилось с тех пор, как Джипстер 6.6, CustomParameterizedException устарело в пользу библиотеки задач Zalando. Вы можете увидеть, как jhipster использует его в ExceptionTranslator.
Вот как это работает сейчас
throw Problem.builder()
.withStatus(Status.BAD_REQUEST)
.withTitle("Out of stock")
.with("message","myjhipsterApp.myentity.error.itBeAllGone")
.with("param1", "hello there").with("param2", "more hello")
.build();
Пользовательские сообщения об ошибках переводятся и находятся в вашем myentity.json, а не в global.json.
для получения дополнительной информации о том, как обрабатывать ошибки Spring MVC REST, JHipster использует Веб-библиотека Zalando's Problem Spring для предоставления расширенных сообщений об ошибках на основе JSON.
похоже, CustomParameterizedException больше не генерируется, моя версия jhipster 7.3.1