Better error handling
This commit is contained in:
parent
86c6a3ad35
commit
0657fac98d
1 changed files with 18 additions and 17 deletions
|
@ -7,38 +7,39 @@ import { fileChangeEventToMsg } from "./messageGenerators";
|
||||||
import type { Signal } from "signal-js";
|
import type { Signal } from "signal-js";
|
||||||
import { Message } from "../interfaces";
|
import { Message } from "../interfaces";
|
||||||
|
|
||||||
function deserialize(data: RawData): Message | void {
|
function deserialize(data: RawData): Message {
|
||||||
let msg;
|
const msg = JSON.parse(data.toString());
|
||||||
|
|
||||||
try {
|
if (typeof msg.jsonrpc !== "string" || msg.jsonrpc !== "2.0" || typeof msg.id !== "number") {
|
||||||
msg = JSON.parse(data.toString());
|
throw Error("Malformed data received.");
|
||||||
} catch (err) {
|
|
||||||
return console.log(err);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof msg.jsonrpc !== "string" || msg.jsonrpc !== "2.0" || typeof msg.id !== "number") return;
|
|
||||||
|
|
||||||
const id: number = msg.id;
|
const id: number = msg.id;
|
||||||
const request = messageTracker.get(id);
|
const request = messageTracker.get(id);
|
||||||
|
|
||||||
if (typeof request?.method !== "string") return;
|
if (typeof request?.method !== "string") {
|
||||||
else if (msg.error != null) return { jsonrpc: "2.0", error: msg.error, id };
|
throw Error("Malformed JSON received.");
|
||||||
else if (msg.result == null) return;
|
} else if (msg.error != null) {
|
||||||
|
throw Error(msg.error);
|
||||||
|
} else if (msg.result == null) {
|
||||||
|
throw Error("Malformed JSON received.");
|
||||||
|
}
|
||||||
|
|
||||||
return { jsonrpc: "2.0", method: request.method, result: msg.result, id };
|
return { jsonrpc: "2.0", method: request.method, result: msg.result, id };
|
||||||
}
|
}
|
||||||
|
|
||||||
function isStringArray(s: Array<unknown>): s is string[] {
|
export function isStringArray(s: Array<unknown>): s is string[] {
|
||||||
return s.every((s) => typeof s === "string");
|
return s.every((s) => typeof s === "string");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function messageHandler(signaller: Signal, data: RawData, paths: Map<string, Stats>) {
|
export function messageHandler(signaller: Signal, data: RawData, paths: Map<string, Stats>) {
|
||||||
const incoming = deserialize(data);
|
let incoming;
|
||||||
|
|
||||||
if (incoming == null) {
|
try {
|
||||||
return console.log("Malformed data received.");
|
incoming = deserialize(data);
|
||||||
} else if (incoming.error) {
|
} catch (err) {
|
||||||
return console.log(incoming.error);
|
if (err instanceof Error) return console.log(err.message);
|
||||||
|
else throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (incoming.method) {
|
switch (incoming.method) {
|
||||||
|
|
Loading…
Add table
Reference in a new issue