Javascript 角度-定义HttpClient.post()的错误类型

Javascript 角度-定义HttpClient.post()的错误类型,javascript,angularjs,angular,typescript,rxjs,Javascript,Angularjs,Angular,Typescript,Rxjs,是否可以将返回错误的类型设置为HttpClient.post()?我想强制使用此服务的任何人使用在其错误界面中定义的属性 例如: // user.service.ts sendData(data: User) { return this.http .post<User>(`${BASE_ENDPOINT}/user`, data, { withCredentials: true })

是否可以将返回错误的类型设置为
HttpClient.post()
?我想强制使用此服务的任何人使用在其错误界面中定义的属性

例如:

// user.service.ts
    sendData(data: User) {
        return this.http
          .post<User>(`${BASE_ENDPOINT}/user`, data, {
            withCredentials: true
          })
      }

// user.component.ts
    this.user.sendData(null)
      .subscribe(
        (success: User) => console.log(success),
        (error: ResponseErrorUser) => console.log(error)
      );
//user.service.ts
sendData(数据:用户){
返回此文件。http
.post(${BASE\u ENDPOINT}/user`,数据{
证书:正确
})
}
//user.component.ts
this.user.sendData(null)
.订阅(
(success:User)=>console.log(success),
(错误:ResponseErrorUser)=>console.log(错误)
);

您可以使用Rxjs操作符catchErrorthrowError捕捉错误,将其映射到自定义对象并抛出此对象

import { catchError, throwError } from 'rxjs/operators';
...
...
// user.service.ts
sendData(data: User) {
  return this.http
    .post<User>(`/api/v1/not-available`, data, {
      withCredentials: true
    })
    .pipe(
      catchError(err => {
        return throwError({
          statusCode: err.status,
          msg: err.message
        });
      })
    );
}

// user.component.ts
this.sendData(null).subscribe(
  (success: User) => console.log(success),
  (error: { statusCode: number; msg: string }) => console.error(error)
);
从'rxjs/operators'导入{catchError,throwError};
...
...
//user.service.ts
sendData(数据:用户){
返回此文件。http
.post(`/api/v1/not available`),数据{
证书:正确
})
.烟斗(
catchError(err=>{
回击投手({
状态代码:err.status,
msg:err.message
});
})
);
}
//user.component.ts
此文件为.sendData(null).subscribe(
(success:User)=>console.log(success),
(错误:{statusCode:number;msg:string})=>console.error(错误)
);

有关自定义错误处理的更多信息,我建议您仔细阅读


希望这有帮助。干杯,快乐编码

所以,您想将
ResponseErrorUser
更改为来自
HttpClient.post()
的返回值还是什么?我想强制同事使用
error:ResponseErrorUser
而不是
error:any
。我已经尝试过了。问题是,您可以在错误中使用任何。我希望该错误只接受一个特定类型。@据我所知,无法强制抛出错误的类型定义。您所能做的就是使用JSdocs规范为您的方法编写文档,如图所示。如果您担心客户端可能无法正确处理错误,请在抛出之前将自定义错误对象记录在控制台日志中,以便在调试时将其保存在控制台中。非常感谢您花费时间和精力提供帮助。我相信我会选择使用JSdocs的@Shravan想法。谢谢