【问题标题】:JHipster custom error message translationJHipster 自定义错误信息翻译
【发布时间】:2021-02-10 03:27:50
【问题描述】:

如何使用 Angular UI 翻译 JHipster App 中的自定义错误消息?

我添加了自定义异常处理程序:

    @ExceptionHandler
    default ResponseEntity<Problem> handleSomeBusinessException(final SomeBusinessException exception, final NativeWebRequest request) {

        final Problem problem = Problem.builder()
            .withStatus(UNPROCESSABLE_ENTITY)
            .with("BusinessException", SomeBusinessException .class.getName())
            .with("BusinessMessage", exception.getMessage())
            .build();

        return create(exception, problem, request);
    } 

接下来我修改了alert-error.component.ts

  this.httpErrorListener = eventManager.subscribe('someApp.httpError', (response: JhiEventWithContent<HttpErrorResponse>) => {
      const httpErrorResponse = response.content;
      switch (httpErrorResponse.status) {

        case 422:
          this.addErrorAlert(httpErrorResponse.error.BusinessMessage);
          break;

不幸的是,当我运行应用程序并抛出 SomeBusinessException 时,我在 UI 中看到以下内容:

translation-not-found[一些与 SomeBusinessException]

你能告诉我在哪里可以介绍我的BusinessMessage的翻译吗?

更新: 我检查了 src\main\webapp\i18n\en\error.json 但它绑定到 http.code,而不是消息本身

【问题讨论】:

  • 你需要在前端的json翻译文件中创建一个专门的翻译。它应该在src/main/webapp/i18n/en/error.json
  • 如何指定我希望使用 BusinessMessage 进行翻译,而不是使用 http 代码?我有多个业务层异常,都有 422 代码
  • 你可以使用例如使用业务异常的简单类名作为翻译键而不是代码。据我所知,BusinessMessage 是异常消息,它可能不是一个好的翻译键。

标签: angular spring-boot exception jhipster


【解决方案1】:

这可以使用简单的异常名称来完成。此外,您可以传递参数,以替换为 ngx-translate

首先,您需要在问题中传递自定义参数:

@ExceptionHandler
default ResponseEntity<Problem> handleSomeBusinessException(final SomeBusinessException exception, final NativeWebRequest request) {

    final Problem problem = Problem.builder()
        .withStatus(UNPROCESSABLE_ENTITY)
        .with("businessException", SomeBusinessException.class.getSimpleName())
        .with("parameterKey", "some value goes here")
        .build();

    return create(exception, problem, request);
} 

其次是AlertErrorComponent的构造函数:

constructor(private alertService: JhiAlertService, private eventManager: JhiEventManager, translateService: TranslateService) {
...
     switch (httpErrorResponse.status) {
        ...
        case 422:
          this.addErrorAlert('', 'business.' + httpErrorResponse.error.businessException, httpErrorResponse.error);
          break;

三是提供翻译参数(ngx-translate支持):

src/main/webapp/i18n/en/error.json

{
  "business": {
    "SomeBusinessException ": "Translated text goes here. {{parameterKey}}",
  }
  ...
}

{{parameterKey}} 将被 ngx-translate 替换为 "some value goes here"

因此您将在屏幕上看到以下消息:

翻译的文本放在这里。这里有一些价值

您也可以查看完整源代码here

【讨论】:

  • 感谢您在此处提供详细答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
  • 2014-01-29
  • 2020-10-18
相关资源
最近更新 更多