Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch
block instead of utilizing the .catch
observable operators for error handling in an Angular project. This approach was unfamiliar to me, prompting me to suggest implementing the built-in .catch
observable operator instead. Here is a TypeScript example of what I observed:
public getSomething(id: string): Observable<any> {
try {
return this.http.get('someurl/someparam')
.map((res) => res.json().data);
} catch (e) {
throw new Error('Error with getSomething()');
}
}
Despite my suggestion, there was resistance from the team arguing that it would not impact performance in terms of memory or network. However, I pointed out that the try/catch block does not accurately capture errors from the HTTP request. Therefore, I am curious to know whether wrapping the http.get
in a try / catch
indeed affects performance. Additionally, I always believed that try / catch
was primarily used for synchronous code rather than asynchronous operations.
If my question seems vague or inappropriate, please feel free to let me know, and I will remove it. I am eager to hear other developers' perspectives on this matter.