Add error code and message

This commit is contained in:
Ethan Lane 2023-09-13 10:58:55 +01:00
parent e10bdaf115
commit a56e448b88
5 changed files with 35 additions and 2 deletions

View file

@ -0,0 +1,6 @@
export enum ErrorCode {
Unknown,
FailedToFetchReddit,
UnableToParseJSON,
NoImageResultsFound,
}

View file

@ -0,0 +1,5 @@
export default class ErrorMessages {
public static readonly FailedToFetchReddit = "Failed to fetch result from Reddit";
public static readonly UnableToParseJSON = "Unable to parse the JSON result";
public static readonly NoImageResultsFound = "No image results found in response from Reddit";
}

6
src/contracts/IError.ts Normal file
View file

@ -0,0 +1,6 @@
import { ErrorCode } from "../constants/ErrorCode";
export default interface IError {
Code: ErrorCode;
Message: string;
}

View file

@ -1,6 +1,8 @@
import IError from "./IError.js";
import IRedditResult from "./IRedditResult.js";
export default interface IReturnResult {
IsSuccess: boolean;
Result?: IRedditResult;
Error?: IError;
}

View file

@ -3,6 +3,8 @@ import IRedditResult from "./contracts/IRedditResult.js";
import fetch from "got-cjs";
import { List } from 'linqts';
import IFetchResult from "./contracts/IFetchResult.js";
import { ErrorCode } from "./constants/ErrorCode.js";
import ErrorMessages from "./constants/ErrorMessages.js";
const sortable = [
'new',
@ -17,7 +19,11 @@ export default async function randomBunny(subreddit: string, sortBy?: string): P
if (!result) {
return {
IsSuccess: false
IsSuccess: false,
Error: {
Code: ErrorCode.FailedToFetchReddit,
Message: ErrorMessages.FailedToFetchReddit,
},
}
}
@ -25,7 +31,11 @@ export default async function randomBunny(subreddit: string, sortBy?: string): P
if (!json) {
return {
IsSuccess: false
IsSuccess: false,
Error: {
Code: ErrorCode.UnableToParseJSON,
Message: ErrorMessages.FailedToFetchReddit,
},
}
}
@ -40,6 +50,10 @@ export default async function randomBunny(subreddit: string, sortBy?: string): P
if (dataWithImages.length == 0) {
return {
IsSuccess: false,
Error: {
Code: ErrorCode.NoImageResultsFound,
Message: ErrorMessages.NoImageResultsFound,
},
};
} else {
random = Math.floor((Math.random() * (dataWithImages.length - 1)) + 0); // Between 0 and (size - 1)