如何使用 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/