JHipster自定义错误消息翻译

时间:2020-10-27 19:14:17

标签: angular spring-boot exception jhipster

如何使用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,而不是消息本身

1 个答案:

答案 0 :(得分:2)

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

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

翻译后的文字在这里。这里有些价值

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