Friday, 17 March 2017

Error handling pattern for Node.js REST API with Angular 2 front end

What is considered to be the standard approach when developing Angular 2 web app with REST API developed in Node.js?

I'd like my REST API to return JSON object in all cases, including all kinds of errors (with the exception of unhandled errors, of course). It seems appropriate to return the response with the matching http status code (2xx for success, 4xx or 5xx for errors). Alternative way would be to always respond with status 200 and include status="error" property in the response JSON object, along with error description and metadata.

At the front-end, however, things get complicated. The errors can be thrown also by the client-side code. The http request error catching must be implemented via .catch() method of the promise object returned by http.get() or http.post() call. Since the response processing happens asynchronously, there's no point throwing the error now with throw statement, as there would be nobody to catch it. However, all normal JavaScript calls must be wrapped in try...catch statements, so that the errors are properly processed. There must exist some good approach/pattern how to handle the both kind of errors, so that I don't have to come up with my own way. Perhaps there are the standard ways, or best practices how to handle this?



via Passiday

No comments:

Post a Comment