Skip to content

Instantly share code, notes, and snippets.

@juanbrusco
Created June 27, 2022 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanbrusco/b597d08b8dfff3105efd95763ff2b885 to your computer and use it in GitHub Desktop.
Save juanbrusco/b597d08b8dfff3105efd95763ff2b885 to your computer and use it in GitHub Desktop.
NodeJS fetch handling error
router.post('/endpointname', async function (req, res, next) {
let bodyObj = { "x": {} };
let requestURL = "https://reqres.in/api/register";
let requestOptions = {
method: "POST",
body: JSON.stringify(bodyObj),
headers: { 'Content-Type': 'application/json' }
};
try {
const apiResponse = await fetch(requestURL, requestOptions);
let r = checkStatus(apiResponse);
const json = await r.json()
res.send(json)
} catch (err) {
returnErrorResponse(res, err, "endpointname");
}
});
var checkStatus = function (response) {
if (!response.ok) {
const responseError = {
statusText: response.statusText,
status: response.status
};
throw (responseError);
}
return response;
}
var returnErrorResponse = function (res, err, id) {
const status = err.status ? err.status : 500;
const error = err.message ? err.message : (err.statusText ? err.statusText : err);
_logger.error(`ERROR: ${id}`);
_logger.error(`ERROR: ${status}-${error}`);
return res.status(status).send({
message: `ERROR: ${id}`,
err: error
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment