Angular ajax загрузка файла не перехватывает 500 HTTP-ответ - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь поймать 500 ошибок при загрузке файла, но я не могу этого сделать. Я попытался добавить несколько типов перехватов в коде, но ни один из них не сработал.

Это основной метод загрузки в моем сервисе:

    private uploadFile(endpoint: string, uploadModel: UploadFileModel): Observable<number | null> {
        uploadModel.formData.append('file', uploadModel.file);
        return this._httpClient
            .post(endpoint, uploadModel.formData, {
                reportProgress: true,
                observe: 'events'
            }).pipe(map(event => {
                switch (event.type) {
                    case HttpEventType.UploadProgress:
                        const progress = Math.round(100 * event.loaded / event.total) / 100;
                        uploadModel.progress = progress;
                        return progress;
                    case HttpEventType.Response:
                        console.log('response', event.body);
                        return event.body;
                }
            })) as Observable<number | null>;
    }

Затем я называю его так:

const subscription = this._presentationService
    .uploadFile(endPoint, model)
    .subscribe({
        next: res => {
            if (typeof res === 'number' && res >= 1) {
                this.presentationFile.step++;
                this.presentationFile.progress = 0;
                subscription.unsubscribe();
                return;
            } else {
                console.log('res', res);
            }
            return this.setStepComplete(false);
        },
        error: err => console.log('err', err),
        complete: () => console.log('complete')
    });

Всякий раз, когда создается 500, все, что выводится на консоль, выглядит следующим образом:

Console

Я пытаюсь Перехватите эти 500 ошибки, чтобы отобразить сообщение об ошибке для пользователя.

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Похоже, что я могу уловить ошибку, прикрепив subscription и pipe к объекту post без цепочки.

Проблема здесь в том, что я не получаю тело ответа, как он возвращается пустым.

const client = this._httpClient
    .post(endpoint, uploadModel.formData, {
        reportProgress: true,
        observe: 'events'
    });

client.subscribe({
    error: error => console.log('error', error)
});

return client.pipe(map(event => {
    switch (event.type) {
        case HttpEventType.UploadProgress:
            const progress = Math.round(100 * event.loaded / event.total) / 100;
            uploadModel.progress = progress;
            return progress;
    }
})) as Observable<number | null>;
0 голосов
/ 11 марта 2020

Я думаю, у вас есть ошибочный { в подписке.

Попробуйте:

const subscription = this._presentationService
    .uploadFile(endPoint, model)
    .subscribe(res => { // !! change here !!
            if (typeof res === 'number' && res >= 1) {
                this.presentationFile.step++;
                this.presentationFile.progress = 0;
                subscription.unsubscribe();
                return;
            } else {
                console.log('res', res);
            }
            this.setStepComplete(false); // this return is unnecessary, can't return in subscribe block.
        },
        (error: err) => { 
                        console.log('In error !!'); 
                        console.log('err', err); 
        },
        () => console.log('complete') // make sure you see complete.
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...