我如何做一个try / catch为我的特定API调用示例?

所以我的问题是非常具体的。 每当我从我的页面运行这个位,我得到一个错误,如果我不input我需要在API中search正确的ID。 由于查询string不正确,它不知道该做什么,因此无法进行有效的API调用。 如何redirect到不同的页面?如果有这样的错误,或者如何阻止它停止程序? 我假设有一个尝试在这里,但我尝试了多种不同的方式,我仍然困惑,因为它不工作。 请帮助! 我是新来的…这是片段。 如果“bnetID”不是有效的ID,则代码的请求部分是发生错误的地方。 如果它是有效的,它运行得非常好…

// Make a GET request to the /results page (When submit is pressed) app.get("/results", function(req, res){ // Retrieve bnetID and REGION from the FORM var bnetID = req.query.bnetID; var region = req.query.region; // Replace the # with a - bnetID = bnetID.replace("#", "-"); // Create the query string var url = "http://ow-api.herokuapp.com/profile/pc/"+ region +"/"+bnetID; // Make the API request request(url, function(err, response, body){ if(err){ console.log(err); } else { var playerData = JSON.parse(body); playerData = findImportantData(bnetID, playerData); checkIfExists(bnetID, playerData); res.render("results", {data: playerData}); } }) }); 

如果出现错误,为什么不处理你想要做的事情?

  if(err){ console.log(err); // change this to whatever you want to do }