[英]How do I return an error if value is undefined in Node/Javascript?
我正在运行查询以返回一些数据
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
如何检查 resultSpec 是否未定义,如果是,则抛出错误并停止执行? 我试过return resultSpec || throw new Error()
return resultSpec || throw new Error()
但是当我尝试时会出现语法错误。
只需使用if
语句:
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
if (!resultSpec) throw new TypeError('Spec is undefined');
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
正如其他人所提到的,如果您不打算在catch
块中进行任何错误处理,而只是简单地重新抛出错误,那么这里不需要try/catch
,因为您可以让调用getIngress
处理它
if (resultSpec == undefined) throw Error("The result is undefined")
如果您不处理 function 中的错误,则不需要 try 和 catch 语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.