Angular + Core API: как перехватить тело ошибки ответа на запрос - PullRequest
0 голосов
/ 07 сентября 2018

Я хочу перехватить сообщение об ошибке вместо имени ошибки.

В настоящее время используется перехватчик в 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);
        }))
    }
}

Но он возвращает только «Bad Request» вместо сообщения об ошибке от 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 ]

0 голосов
/ 12 сентября 2018

Как правило, вам не нужно использовать API низкого уровня, такой как HttpInterceptor, поскольку 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 для более точной обработки ошибок.

0 голосов
/ 08 сентября 2018

Это решение проблемы, а не:

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

Я использовал другую трубу:

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