如何处理流中对象的新属性
How to handle new properties to object in flow
我有一个函数可以检查 fetch
响应的状态代码并抛出错误,以便我可以使用 catch 来处理它。我使用的流程不喜欢我将响应传递给错误对象,我需要它来处理正确的状态代码并获得良好的 promis 链接。
const StatusCodeHandler = (response: { statusText: string, ok: string }) => {
if (response.ok) return response;
const error = new Error(response.statusText);
error.response = response;
throw error;
};
我使用的时候应该是这样的:
fetch(url).then(StatucCodeHandler)
.then(respone=>response.json())
.catch(error=>handleError(error.response.status));
....
在handleError
我会根据状态码做具体的操作
什么是正确的方法来做到这一点?
第二种方法 then
和 catch
是更好的方法。由于更好地处理异步操作、更好地定义异步逻辑中的控制流等优势。
最合适的方法可能是通过 subclassing Error
.
定义自定义错误 class
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);
};
(Try)
如果您使用的是早于 7 的 babel 版本,您需要 transform-builtin-classes 允许子类化内置 Error
。
我有一个函数可以检查 fetch
响应的状态代码并抛出错误,以便我可以使用 catch 来处理它。我使用的流程不喜欢我将响应传递给错误对象,我需要它来处理正确的状态代码并获得良好的 promis 链接。
const StatusCodeHandler = (response: { statusText: string, ok: string }) => {
if (response.ok) return response;
const error = new Error(response.statusText);
error.response = response;
throw error;
};
我使用的时候应该是这样的:
fetch(url).then(StatucCodeHandler)
.then(respone=>response.json())
.catch(error=>handleError(error.response.status));
....
在handleError
我会根据状态码做具体的操作
什么是正确的方法来做到这一点?
第二种方法 then
和 catch
是更好的方法。由于更好地处理异步操作、更好地定义异步逻辑中的控制流等优势。
最合适的方法可能是通过 subclassing 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);
};
(Try)
如果您使用的是早于 7 的 babel 版本,您需要 transform-builtin-classes 允许子类化内置 Error
。