如何将参数传递给JHipster中的自定义错误消息?

时间:2019-03-13 01:31:11

标签: angular spring-boot jhipster

我仍在学习JHipster,所以今天我还是要靠自己制作somme验证应用程序,并尝试向前端发送有意义的错误消息

这是我尝试过的

在我的控制器中,我有以下内容:

/**
 * 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}} "
    },

我显示了我的消息,但没有日期值。

如您所见,我想提及用作错误消息变量的日期,但是我不知道如何,所以如何将这个日期值添加到错误消息中?

2 个答案:

答案 0 :(得分:1)

嗨,经过一整天的代码学习,我发现Jhipster已经在web/rest/errors包中建立了一个错误处理机制,其中充满了Throwable似乎很方便,就我而言,它是{{1 }}

我所做的很简单

首先,我的控制器创建课程变为:

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

这样,当checkLessonTime失败时,我会得到带有参数的所需错误消息

感谢您的关注,希望这对其他初学者有所帮助。

有关更多详细信息,请阅读"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}} " }, 的类代码。

答案 1 :(得分:1)

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的错误消息。

相关问题