javascript - 如何修复 fetch() 方法引发的无法获取错误?
问题描述
我在 localhost 上有一个单独的基本 nodejs 服务器和一个单独的前端。
当我在服务器离线时尝试获取时,fetch()
抛出failed to fetch * 错误。因此,为此,我尝试通过检查响应来处理或捕获该错误。好的,喜欢
if (!response.ok) throw Error(response.statusText)
尽管它捕获了错误,但它仍然会引发错误。即使我试图控制台记录它。
if (!response.ok) return console.log(response.statusText)
这里是接口。
export interface
CommunicatorParameter {
endUrl: string;
}
interface ErrorResponse {
message: string;
}
interface V01List {
tittle: string;
url: string;
}
type V01ListData = Array<V01List>;
type ReleasedVersionsResponse = Array<string>;
type CurrentVersionResponse = string;
interface SuccessResponse{
data: V01ListData | ReleasedVersionsResponse | CurrentVersionResponse ;
}
export type ServerResponse = SuccessResponse | ErrorResponse;
export type CommunicatorResponse = SuccessResponse['data'];
下面是帮助与服务器通信的服务功能。另外,我希望这个函数应该返回直接数据(键)值。
interface SuccessResponse{
data: V01ListData | ReleasedVersionsResponse | CurrentVersionResponse ;
}
// fetchDataFromServer.ts
// these are type and interfaces.
import { CommunicatorParameter, ServerResponse, CommunicatorResponse } from "./declarations/index.js";
// These are helper functions
import { buildValidURL, checkForBadResponse } from "./helpers/index.js";
export async function fetchDataFromServer({ endUrl }: CommunicatorParameter): Promise<CommunicatorResponse> {
const fullURL = buildValidURL(endUrl);
const response = await fetch(fullURL, {
method: 'GET'
});
console.log(response.headers)
const jsonParsedData = <ServerResponse>await response.json();
//This function simply checks response and throws an error if the response is not ok.
checkForBadResponse(response, jsonParsedData);
// Here I am doing this because if I return from try/catch or if statement the return type of function does not match and typescript complain about that. I don't think it is a good way to do it. But don't know how to do it.
return ('data' in jsonParsedData) ? jsonParsedData.data : [];
}
我还有另一个函数可以帮助从使用上述通信器乐趣的服务器获取版本数据。
// fetchCurrentVersion.ts
import { fetchDataFromServer } from "../services/fetchDataFromServer.js";
export async function fetchCurrentListVersion() {
const END_URL = "/current_version";
try {
const response = await fetchDataFromServer({ endUrl: END_URL });
// Here I am checking the type of response/data which is returned by communicator as my need, see the interface SuccessResponse data key.
if (typeof response === 'string') {
return response;
}
} catch (error) {
console.log(error.message)
}
// fallback return value;
return "v0.0";
}
这种方法好吗?我觉得仍然有更好的方法来做到这一点。如果你能帮忙,请
解决方案
推荐阅读
- google-apps-script - 某些单元格的“加载”问题。我的 Google 电子表格未更新,并且 google 应用程序脚本无法正常工作
- javascript - 节点服务器未运行:退出而没有任何输出
- javascript - javascript错误:ShadowRoot上不允许使用Robot Framework进行鼠标悬停的方法“elementsFromPoint”
- android - 由于后台位置权限,应用在 Play 商店被拒绝
- android - Flow 提供 null 作为房间数据库中的数据
- python - 如何从 csv 获取唯一值?
- promise - 如何最好地实现 Promise 信号量?
- spring-boot - Spring Cloud Gateway Netty 指标
- amazon-sqs - 如果消息正文未更改(仅更改参数),是否有办法再次向 SQS(FIFO)发送消息?
- amazon-web-services - EC2 实例策略(配置文件)不允许从 ecr 拉取图像