如何将参数传递给JHipster中的自定义错误消息? [英] How pass params to custom error message in JHipster?

查看:94
本文介绍了如何将参数传递给JHipster中的自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I m still learning JHipster, So today I though about making somme validation exerices by my self, and to try to send meaningfull error messages to my frontend

这是我尝试过的

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

In my controller I have the following :

/**
 * 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 的错误请求响应,然后下一步是在前端进行一些更改这个

as you see if the check lesson time fails I have to send a bad request response with failure code EK_L_C01 then my next step ws to make a little change in the front end where I got to make this

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 中,如下所示

then I added the translation of the code in my global.json as below

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

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

I have my message displayed but there is no date value.

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

As you see I want to mention the date used as error message variable but I dont know how, so How can I add this date value to my error message ?

推荐答案

Jhipster 6.6 以来,此情况已完全改变,不推荐使用CustomParameterizedException,而使用Zalando的问题库.您可以在ExceptionTranslator中看到jhipster在使用它.

This has completely changed since Jhipster 6.6, CustomParameterizedException is deprecated in favor of Zalando's Problem Library. You can see jhipster using it in the 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中.

Custom error messages are translated and are in your myentity.json, not typically in global.json.

有关如何处理Spring MVC REST错误的更多信息,JHipster使用 Zalando的问题Spring Web库,以便提供基于JSON的丰富错误消息.

for more info on how to handle Spring MVC REST errors, JHipster uses Zalando’s Problem Spring Web library, in order to provide rich, JSON-based error messages.

这篇关于如何将参数传递给JHipster中的自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆