Javascript 如何处理流中对象的新属性
我有一个函数,它检查Javascript 如何处理流中对象的新属性,javascript,flowtype,Javascript,Flowtype,我有一个函数,它检查fetch响应的状态代码,并抛出一个错误,以便我可以使用catch来处理它。我使用的是flow,它不喜欢我将响应传递给Error对象,我需要它来处理正确的statuscode和一个好的promis链接 const StatusCodeHandler=(响应:{statusText:string,ok:string})=>{ if(response.ok)返回响应; 常量错误=新错误(response.statusText); error.response=响应; 投掷误差;
fetch
响应的状态代码,并抛出一个错误,以便我可以使用catch来处理它。我使用的是flow,它不喜欢我将响应传递给Error对象,我需要它来处理正确的statuscode和一个好的promis链接
const StatusCodeHandler=(响应:{statusText:string,ok:string})=>{
if(response.ok)返回响应;
常量错误=新错误(response.statusText);
error.response=响应;
投掷误差;
};
当我使用它时,它应该是这样的:
fetch(url)。然后(staticcodehandler)
.then(respone=>response.json())
.catch(error=>handleError(error.response.status));
....
在handleError
中,我将根据状态码执行特定操作
用flow做这件事的最佳方法是什么?第二种方法是
然后和捕获。由于更好地处理异步操作、异步逻辑中更好的控制流定义等优点。最合适的方法可能是通过子类化error
来定义自定义错误类
class RequestError extends Error {
response: Response;
constructor(message: string, response: Response) {
super(message);
this.response = response;
this.message = message;
}
};
const StatusCodeHandler = (response: Response) => {
if (response.ok) return response;
throw new RequestError(response.statusText, response);
};
()
如果您使用的是早于7的babel版本,您将希望允许对内置的错误进行子分类您是否引用了我文章的第二个代码块?这正是我的目标,但为此,我需要错误中的响应,以便我可以访问handleError中的不同状态代码
class RequestError extends Error {
response: Response;
constructor(message: string, response: Response) {
super(message);
this.response = response;
this.message = message;
}
};
const StatusCodeHandler = (response: Response) => {
if (response.ok) return response;
throw new RequestError(response.statusText, response);
};