对于我来说,fny的答案确实可以解决所有问题。由于fetch不会引发错误,因此我们需要自己引发/处理错误。用异步/等待发布我的解决方案。我认为这更具前瞻性和可读性
解决方案1:不引发错误,请自行处理错误
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
在这里,如果遇到错误,我们将构建一个错误对象,普通的JS对象并返回它,缺点是我们需要在外部进行处理。如何使用:
const userSaved = await apiCall(data);
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved);
return;
}
debug.log('Success saving user', userSaved);
解决方案2:使用try / catch引发错误
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
在这里,我们抛出并创建了我们创建的错误,因为Error ctor仅批准字符串,Im创建了普通的Error js对象,其用法为:
try {
const userSaved = await apiCall(data);
debug.log('Success saving user', userSaved);
} catch (e) {
debug.log('Failed saving user', userSaved);
}
解决方案3:使用客户错误
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
和:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
希望能有所帮助。
catch
但没有catch
。