我已经编写了一个服务来调用另一个API服务。但是有时,当我致电服务时会收到错误消息。这样的错误之一是“找到未绑定参数”,但是我得到的状态码是200。所以,我希望200对于这种错误输出来说不是正确的状态码。
在这种情况下如何获取正确的状态代码?
我目前用于获取状态代码的方法是response.statusCode
function apiCall(url, protocol) {
function externalApi(url, callback) {
try {
var https = $.require(protocol);
var request = https.request(url, function (response) {
var str = '';
var statusCode = response.statusCode;
var headers = response.headers;
response.on('data', function (data) {
str += data;
});
response.on('end', function () {
console.log("Data is " + str);
console.log("Status Code is " + statusCode);
console.log("Header is " + JSON.stringify(headers));
callback(str, statusCode);
});
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
console.log('Problem with request: ' + e);
});
request.end();
} catch (err) {
console.log("the error is" + err);
var errCode = err.statusCode;
callback(err, 999);
}
}
var status = function (data, statusCode) {
var callStatus = {};
if (statusCode == 200) {
callStatus.retrievedData = data;
callStatus.statusCode = statusCode;
callStatus.MESSAGE = "API successfully called";
} else if (statusCode == 999) {
callStatus.MESSAGE = "API call failed";
callStatus.errorDetails = data;
callStatus.errorDescription = "Error generated from Catch Block";
} else {
callStatus.details = data;
callStatus.statusCode = statusCode;
}
console.log(callStatus);
};
externalApi(url, status);
}
我得到的是错误消息,但状态代码为200。但是我需要的是带有确切错误状态代码的错误消息。