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

问题描述 投票:0回答:2

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

目前在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");
    }
}
c# .net angular .net-core asp.net-core-webapi
2个回答
0
投票

这是问题的解决方案,而不是:

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

我使用了不同的管道:

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

0
投票

通常,您不需要像HttpInterceptor那样使用低级API,因为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的详细信息来更具体地处理错误。

© www.soinside.com 2019 - 2024. All rights reserved.