Tuesday, 4 April 2017

Is it safe to put error handling in the end event of a Node http request stream?

Looking to log an error and reject a request if a node request stream returns any statusCode other than 200 range, but I want to get the response from the request if available even if it fails because it sometimes has useful information on failure cause. So my question is if I put my check for statusCode inside the end event, is there a possibility it will never be called and the program will hang? Is there a better way to get the response body and reject on statusCode?

const request = http.get(url, (response) => {
            const body = [];
            response.on('data', (chunk) => body.push(chunk));
            response.on('end', () => {
                // handle http errors
                if (response.statusCode < 200 || response.statusCode > 299) {
                    reject(new ErrorClass(response.statusCode, body.join('')));
                } else {
                    resolve(body.join(''))
                }
            });
        });



via EMC

No comments:

Post a Comment