Tried to improve error handling on book upload

This commit is contained in:
Dmitriy Shishkov 2021-08-09 14:05:57 +03:00
parent 4f558b8530
commit fa38e0054b
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
3 changed files with 13 additions and 3 deletions

View File

@ -1,4 +1,5 @@
import { getBook, getBooks, saveBook } from "./db";
import { composeResponseStatus } from "./utils";
export interface PathHandler {
/** Path start for handler */
@ -31,7 +32,7 @@ export const handleBookUpload = async (request: Request) => {
return new Response(JSON.stringify(book));
} else throw new Error(res.status.toString() + res.statusText);
} catch (err) {
return new Response(JSON.stringify(err));
return new Response(JSON.stringify(err), composeResponseStatus(err));
}
};
@ -51,5 +52,8 @@ export const handleBook = async (request: Request, hash: string) => {
const book = await getBook(hash);
if (book) return new Response(JSON.stringify(book));
return new Response("No such book :(");
return new Response(null, {
status: 404,
statusText: "No such book :(",
});
};

View File

@ -7,3 +7,9 @@ export const getHash = (path: string) => {
return path.substr("/book/".length, hashLength);
};
export const composeResponseStatus = (err: Error): ResponseInit => {
if (err.name === "NetowrkError")
return { status: 503, statusText: err.message };
else return { status: 500, statusText: "Something bad happened (IDK)" };
};

View File

@ -45,7 +45,7 @@ export const validateResponse = (content: unknown): content is BookT => {
if (!(key in content)) {
if (process.env.NODE_ENV === "development")
console.error(`${key} is not specified in server response`);
return false;
throw new Error(`${key} is not specified in server response`);
}
return true;