angular - JHipster 自定义错误消息翻译

标签 angular spring-boot exception jhipster

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

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

    @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[Some business message related to SomeBusinessException]

您能否告知我可以在哪里翻译我的BusinessMessage

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

最佳答案

这可以使用简单的异常名称来完成。此外,您还可以传递参数,并用 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 替换为“此处有一些值”

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

Translated text goes here. some value goes here

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

关于angular - JHipster 自定义错误消息翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64561424/

相关文章:

angular - ionViewDidLoad() 函数的目的是什么?

javascript - 无法使用 firebase 在 angular 4 中启用通知

angular - 如何在Angular 8中显示超时错误

angular - 单击输入时如何使 <mat-autocomplete> 显示

java - 负载均衡器后面的 Spring OAuth2 SSO

java - Spring Boot 似乎没有找到 Repository

spring - 创建自动配置 spring 库到 spring-boot 应用程序

java - 避免检查异常

java - 如何捕获事件调度线程 (EDT) 异常?

python - 无限的本地错误 Python