簡體   English   中英

Angular + Core API:如何攔截請求響應錯誤正文

[英]Angular + Core API: How to intercept request response error body

我想截取錯誤消息而不是錯誤名稱。

當前在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");
    }
}

這是解決問題的方法,而不是:

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

我使用了不同的管道:

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

通常,您不需要使用像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的詳細信息以更具體地處理錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM