简体   繁体   中英

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

I want to intercept the error message instead of the error name.

Currently used interceptor in 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);
        }))
    }
}

But it's returning only "Bad Request" instead of the error message from the 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");
    }
}

This is the solution to the problem, instead of:

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

I used a different pipe:

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

Generally you don't need to use low level API like HttpInterceptor, since HttpClient had already provided adequate functions to handle HTTP errors.

Http client service:

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' });
    }

In you app code:

            this.service.addRole(this.userId, roleName)
            .pipe(takeWhile(() => this.alive))
            .subscribe(
            (data) => {
                //handle your data here
            },
            (error) => {
                error(error);
            }

Error handling in details:

    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

}

And you may go to the details of HttpErrorResponse to handle errors more specifically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM