I am trying to catch 500
errors from a file upload, but I cannot seem to do so. I have tried adding multiple types of catches in the code but none have worked.
This is the main upload method in my service:
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>;
}
I then call it like so:
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')
});
Whenever a 500
is created all that gets printed to the console is the following:
I am trying to catch these 500
errors to display an error message to the user.
I am thinking you have an erroneous {
in the subscribe.
Try:
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.
});
It looks like I can catch the error by attaching a subscription
and a pipe
to the post object without chaining.
The issue here is that I do not get the body of the response, as it comes back empty.
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>;
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.