Created
June 27, 2022 15:04
-
-
Save juanbrusco/b597d08b8dfff3105efd95763ff2b885 to your computer and use it in GitHub Desktop.
NodeJS fetch handling error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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