common-ui/src/lib/services/error-message.service.ts
2022-08-16 12:59:25 +03:00

24 lines
845 B
TypeScript

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class ErrorMessageService {
constructor(private readonly _translateService: TranslateService) {}
getMessage(error: HttpErrorResponse, defaultMessage?: string): string {
return defaultMessage
? (this._translateService.instant(defaultMessage, { error: this._parseErrorResponse(error) }) as string)
: this._parseErrorResponse(error);
}
private _parseErrorResponse(err: HttpErrorResponse): string {
return (
(err?.error?.message?.match('"message":"(.*?)\\"')?.[0].replace(/"message":"|"/gm, '') as string) ||
(err?.error?.message as string)
);
}
}