Rule Definition
Ensure that each web service callback is going to be properly checked in order to make sure you will not miss any problem that occurred in your application and you will give the information to the user.
Remediation
Add a catchError operator to the stream before the subscription or use an error handler function at subscription.
Note that using a catchError operator offers more possibilities since it allows to recover from the error by emitting an alternative fallback value in the stream.
Violation Code Sample
import { ajax } from 'rxjs/ajax';
const apiData = ajax('/api/data').pipe(
map(res => {
if (!res.response) {
throw new Error('Value expected!');
}
return res.response;
}),
);
apiData.subscribe({
next(x) { console.log('data: ', x); }
});
Fixed Code Sample
import { ajax } from 'rxjs/ajax';
import { map, catchError } from 'rxjs/operators';
// Return "response" from the API. If an error happens,
// return an empty array.
const apiData = ajax('/api/data').pipe(
map(res => {
if (!res.response) {
throw new Error('Value expected!');
}
return res.response;
}),
catchError(err => of([]))
);
apiData.subscribe({
next(x) { console.log('data: ', x); },
error(err) { console.log('errors already caught... will not run'); }
});
Reference
https://angular.io/guide/rx-library#error-handling
https://angular.io/guide/rx-library
https://blog.angular-university.io/rxjs-error-handling/
Related Technologies
Technical Criterion
CWE-392 - Missing Report of Error Condition
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.