tillias
tillias

Reputation: 1265

JHipster custom error message translation

How can I translate custom error message in JHipster App with Angular UI?

I have added custom exception handler:

    @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);
    } 

Next I modified 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;

Unfortunately when I run app and SomeBusinessException is thrown I see follwing stuff in UI:

translation-not-found[Some business message related to SomeBusinessException]

Can you please advise where I can introduce translation of my BusinessMessage?

Update: I have checked src\main\webapp\i18n\en\error.json but it is bound to http.code, not to message itself

Upvotes: 2

Views: 849

Answers (1)

tillias
tillias

Reputation: 1265

This can be done using simple name of exception. Additionally you can pass parameters, to be substituted by ngx-translate.

First of all you need to pass custom parameters within a Problem:

@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);
} 

Second is constructor of AlertErrorComponent:

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

Third is to provide translation with parameter (supported by ngx-translate):

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

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

{{parameterKey}} will be substituted by ngx-translate with "some value goes here"

So you will see on screen following message:

Translated text goes here. some value goes here

You can also check full source code here

Upvotes: 4

Related Questions