Angular + Core API:如何拦截请求响应错误正文

我想拦截错误消息而不是错误名称。


目前在 Angular 中使用的拦截器:


@Injectable()

export class ErrorInterceptor implements HttpInterceptor {

    constructor(private authenticationService: AuthenticationService) {}


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(catchError(err => {

            if (err.status === 401) {

                this.authenticationService.logout();

                location.reload(true);

            }               

            const error = err.error.message || err.statusText;

            return throwError(error);

        }))

    }

}

但它只返回“错误请求”而不是来自 API 的错误消息。


public IActionResult Login([FromBody]UserModel user)

    if (userRepository.CheckIfUserExists(user.Username))

    {

        if (userRepository.CheckIfPasswordIsCorrect(user))

        {

            return new JsonResult(userRepository.GetUser(user));

        }

        else

        {

            return BadRequest("Test");

        }

    }

    else

    {

        return BadRequest("Test");

    }

}


慕少森
浏览 184回答 2
2回答

森栏

这是问题的解决方案,而不是:const&nbsp;error&nbsp;=&nbsp;err.error.message&nbsp;||&nbsp;err.statusText;我使用了不同的管道:const&nbsp;error&nbsp;=&nbsp;err.error.message&nbsp;||&nbsp;err.error;

小唯快跑啊

通常你不需要使用像 HttpInterceptor 这样的低级 API,因为 HttpClient 已经提供了足够的函数来处理 HTTP 错误。Http客户端服务:export namespace My_WebApi_Controllers_Client {@Injectable()export class Account {&nbsp; &nbsp; constructor(@Inject('baseUri') private baseUri: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/', private http: HttpClient) {&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* POST api/Account/AddRole?userId={userId}&roleName={roleName}&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; addRole(userId: string, roleName: string): Observable<HttpResponse<string>> {&nbsp; &nbsp; &nbsp; &nbsp; return this.http.post(this.baseUri + 'api/Account/AddRole?userId=' + encodeURIComponent(userId) + '&roleName=' + encodeURIComponent(roleName), null, { observe: 'response', responseType: 'text' });&nbsp; &nbsp; }在您的应用程序代码中:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.service.addRole(this.userId, roleName)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .pipe(takeWhile(() => this.alive))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .subscribe(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (data) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //handle your data here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (error) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error(error);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }详细错误处理:&nbsp; &nbsp; error(error: HttpErrorResponse | any) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let errMsg: string;&nbsp; &nbsp; if (error instanceof HttpErrorResponse) {&nbsp; &nbsp; &nbsp; &nbsp; if (error.status === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errMsg = 'No response from backend. Connection is unavailable.';&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (error.message) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errMsg = `${error.status} - ${error.statusText}: ${error.message}`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errMsg = `${error.status} - ${error.statusText}`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; errMsg += error.error ? (' ' + JSON.stringify(error.error)) : '';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; errMsg = error.message ? error.message : error.toString();&nbsp; &nbsp; }&nbsp; &nbsp; //handle errMsg}你可以去 HttpErrorResponse 的细节来更具体地处理错误。
打开App,查看更多内容
随时随地看视频慕课网APP