Skip to content

Commit

Permalink
dont throw error from sseResponse, remove the catch statement
Browse files Browse the repository at this point in the history
  • Loading branch information
umitcanbal committed Nov 30, 2023
1 parent b1a2ad6 commit b2fe50f
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions _examples/golang-sse/webapp/src/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface WebRpcOptions {

export interface WebRpcStreamOptions<T> extends WebRpcOptions {
onMessage: (message: T) => void;
onError: (error: Error | WebrpcError) => void;
onError: (error: WebrpcError) => void;
onOpen?: () => void;
onClose?: () => void;
}
Expand Down Expand Up @@ -125,12 +125,7 @@ export class Chat implements Chat {
(error) => {
options.onError(error);
}
).catch((error) => {
options.onError(
WebrpcRequestFailedError.new({
cause: `fetch(): ${error.message || ""}`,
}))
})
)
};
}

Expand Down Expand Up @@ -170,25 +165,46 @@ const buildResponse = (res: Response): Promise<any> => {
};

const sseResponse = async (res: Response, options: WebRpcStreamOptions<any>) => {
const { onMessage, onOpen, onClose } = options;

const { onMessage, onOpen, onClose, onError } = options;
if (!res.ok) {
res.json().then((json) => {
const code: number = typeof json.code === "number" ? json.code : 0;
throw (webrpcErrorByCode[code] || WebrpcError).new(json);

onError((webrpcErrorByCode[code] || WebrpcError).new(json));
return;
});
}
if (!res.body) {
throw new Error(`HTTP error, status: ${res.status}`);
onError(WebrpcBadResponseError.new({
status: res.status,
cause: "Invalid response, missing body",
}));
return;
}

onOpen && onOpen();

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

while (true) {
const { value, done } = await reader.read();
let value;
let done;
try {
({ value, done } = await reader.read());
} catch (error) {
let message = "";
if (error instanceof Error) {
message = error.message;
}
options.onError(
WebrpcRequestFailedError.new({
cause: `fetch(): ${message}`,
}))
return;
}
if (done) {
onClose && onClose()
return;
Expand Down

0 comments on commit b2fe50f

Please sign in to comment.