Javascript 有没有一种方法可以在catch中返回错误而不抛出新错误?
我在try中调用了一个自定义错误。我想在catch中返回这个错误,而不抛出新的错误Javascript 有没有一种方法可以在catch中返回错误而不抛出新错误?,javascript,node.js,express,Javascript,Node.js,Express,我在try中调用了一个自定义错误。我想在catch中返回这个错误,而不抛出新的错误 const callSomething = async () => { try { doSomething(); } catch (error) { // This function receive the error with the additional properties, so we need the custom error object customErrorT
const callSomething = async () => {
try {
doSomething();
} catch (error) {
// This function receive the error with the additional properties, so we need the custom error object
customErrorTreatment(error);
}
};
此函数是第一次调用错误的位置
const doSomething = async () => {
try {
// This function throw a custom error class with additional properties
throwApiError({
responseMessage: 'Some error occour',
responseStatus: 500,
});
} catch (error) {
// If I return error, the function callSomething just receive the value without error.
return error;
// I can call throwApiError again, but feels ugly, that is the only way?
return throwApiError({
responseMessage: error.responseMessage
responseStatus: error.status,
});
}
};
这是自定义错误类和函数
export const ApiError = class ApiError extends Error {
constructor({ responseMessage, responseStatus, error }) {
super(error);
this.responseMessage = responseMessage;
this.responseStatus = responseStatus;
}
};
const throwApiError = ({ responseMessage, responseStatus, error }) => {
throw new ApiError({ responseMessage, responseStatus});
};
简而言之,不是,因为要生成错误,您需要抛出
,并且您的方法是错误处理的常用方法。但还有另一种方法可以管理这样的错误:
const callSomething = async () => {
let { result, error } = resdoSomething();
if (error) {
return throwApiError({
responseMessage: error.responseMessage
responseStatus: error.status,
});
}
console.log(result)
// do somethings
};
及
通过这种方式,您可以减少try/catch的数量,简言之,No,因为要生成错误,您需要抛出,并且您的方法是错误处理的常用方法。但还有另一种方法可以管理这样的错误:
const callSomething = async () => {
let { result, error } = resdoSomething();
if (error) {
return throwApiError({
responseMessage: error.responseMessage
responseStatus: error.status,
});
}
console.log(result)
// do somethings
};
及
通过这种方式,您可以减少try/catch的数量,不再调用throwApiError()
。如果你想让承诺继续被拒绝,就抛出错误,这就是承诺的工作原理
或者完全去掉catch()处理程序,这样错误就会自然传播到更高的级别,而无需您的干预。您似乎没有在catch处理程序中执行任何操作,因此您可以将其删除。不要再次调用throwApiError()
。如果你想让承诺继续被拒绝,就抛出错误,这就是承诺的工作原理
或者完全去掉catch()处理程序,这样错误就会自然传播到更高的级别,而无需您的干预。您似乎没有在catch handler中执行任何操作,因此您可以将其删除。谢谢您的回答!我们正在避免这种模式,因为它不会生成状态代码。谢谢你的回答!我们避免使用这种模式,因为它不会生成状态代码。