如何将参数传递给 JHipster 中的自定义错误消息?
How pass params to custom error message in JHipster?
我还在学习 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);
}
然后我在 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 {{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
的 class 代码。
自 Jhipster 6.6 以来,这已完全改变,CustomParameterizedException 已弃用,取而代之的是 Zalando 的问题库。你可以在 ExceptionTranslator 中看到 jhipster 使用它。
这是现在的运作方式
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 Web library,以提供丰富的、基于 JSON 的错误消息。
我还在学习 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);
}
然后我在 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 {{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
的 class 代码。
自 Jhipster 6.6 以来,这已完全改变,CustomParameterizedException 已弃用,取而代之的是 Zalando 的问题库。你可以在 ExceptionTranslator 中看到 jhipster 使用它。
这是现在的运作方式
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 Web library,以提供丰富的、基于 JSON 的错误消息。