Add error codes and error messages to failed results #89

Merged
Vylpes merged 3 commits from feature/53-error-message-return into develop 2023-09-15 15:18:58 +01:00
5 changed files with 35 additions and 2 deletions
Showing only changes of commit a56e448b88 - Show all commits

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"; import IRedditResult from "./IRedditResult.js";
export default interface IReturnResult { export default interface IReturnResult {
IsSuccess: boolean; IsSuccess: boolean;
Result?: IRedditResult; Result?: IRedditResult;
Error?: IError;
} }

View file

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