亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

C#
慕少森 2022-01-09 10:13:41
我想攔截錯誤消息而不是錯誤名稱。目前在 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");    }}
查看完整描述

2 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

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

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

我使用了不同的管道:

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


查看完整回答
反對 回復 2022-01-09
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

通常你不需要使用像 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 的細節來更具體地處理錯誤。


查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 209 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號