Как правило, вам не нужно использовать API низкого уровня, такой как HttpInterceptor, поскольку HttpClient уже предоставил адекватные функции для обработки ошибок HTTP.
Http клиент службы:
export namespace My_WebApi_Controllers_Client {
@Injectable()
export class Account {
constructor(@Inject('baseUri') private baseUri: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/', private http: HttpClient) {
}
/**
* POST api/Account/AddRole?userId={userId}&roleName={roleName}
*/
addRole(userId: string, roleName: string): Observable<HttpResponse<string>> {
return this.http.post(this.baseUri + 'api/Account/AddRole?userId=' + encodeURIComponent(userId) + '&roleName=' + encodeURIComponent(roleName), null, { observe: 'response', responseType: 'text' });
}
В вашем коде приложения:
this.service.addRole(this.userId, roleName)
.pipe(takeWhile(() => this.alive))
.subscribe(
(data) => {
//handle your data here
},
(error) => {
error(error);
}
Обработка ошибок в деталях:
error(error: HttpErrorResponse | any) {
let errMsg: string;
if (error instanceof HttpErrorResponse) {
if (error.status === 0) {
errMsg = 'No response from backend. Connection is unavailable.';
} else {
if (error.message) {
errMsg = `${error.status} - ${error.statusText}: ${error.message}`;
} else {
errMsg = `${error.status} - ${error.statusText}`;
}
}
errMsg += error.error ? (' ' + JSON.stringify(error.error)) : '';
} else {
errMsg = error.message ? error.message : error.toString();
}
//handle errMsg
}
И вы можете перейти к деталям HttpErrorResponse для более точной обработки ошибок.