Reputation: 453
I am building a calendar app that gets data for each day from a (currently mocked) backend. On correct urls for the http.get, this works just fine, though if the url is wrong, or there is no data/json object in the backend for the requested day (for example, weekends don't have any data), I (obviously) get a 404, though the log in the console rarely shows it, instead it always gives me the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Obviously it can't have an expected character there as no Json object exists for the requested day. Checking the Network analysis shows me that it is indeed a 404 error though.
I use the basic http.get and handleError from here https://angular.io/guide/http#subscribe
Code of the service with the http.get:
getDayInfo(date: string): Observable<any> {
return this.gttp.get('somepath/' + date + '/somemoreinfo')
.map(this.extractData, // works just fine
console.log('map running for date: ', date)
)
.catch(this.handleError);
}
private extractData(res: Response) {
if (res != null) {
let body = res.json();;
return body;
} else { // else return an empty dummy json, doesn't really work here
return '[{"id": "", "userId": "", "userName": "", "type": { "name": "" }, "date": {' +
'"startDate": "", "endDate": "", "startTime": "", "endTime": "" } }]'; }
}
private handleError(error: Response | any) {
console.log('Errorhandling triggered');
let errMsg: string;
if (error instanceof Response) {
console.log('Errorhandling if-block'); // this triggers on a 404
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || '' } ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error('Error ', errMsg); // this never appears in the log though
return Observable.throw(errMsg);
}
The goal for me is to catch a 404 instead of having it throw the JSON.parse error I posted earlier and handle it by sending an empty json object (or a dummy json object) instead so the day in the calendar simply displays nothing.
Upvotes: 4
Views: 3176
Reputation:
Your problem is on the line
const body = error.json() || '';
The problem is that when your back-end sends an error (here being a 404), you don't send a JSON object. So if you use error.json()
, don't expect to get a JSON object !
Either you return a JSON error from your back-end, or you don't use the json()
function in your error handler.
When you don't use the json()
function, you also gain access to the status
property (if I recall correctly it's this one) which contains the error code. So you can put conditions on it, like if it's 404, you do what you want.
I hop I made myslef clear, if not, feel free to ask for more details !
Upvotes: 5