Add error codes and error messages to failed results #89
5 changed files with 35 additions and 2 deletions
6
src/constants/ErrorCode.ts
Normal file
6
src/constants/ErrorCode.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
export enum ErrorCode {
|
||||
Unknown,
|
||||
FailedToFetchReddit,
|
||||
UnableToParseJSON,
|
||||
NoImageResultsFound,
|
||||
}
|
5
src/constants/ErrorMessages.ts
Normal file
5
src/constants/ErrorMessages.ts
Normal 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
6
src/contracts/IError.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
import { ErrorCode } from "../constants/ErrorCode";
|
||||
|
||||
export default interface IError {
|
||||
Code: ErrorCode;
|
||||
Message: string;
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
import IError from "./IError.js";
|
||||
import IRedditResult from "./IRedditResult.js";
|
||||
|
||||
export default interface IReturnResult {
|
||||
IsSuccess: boolean;
|
||||
Result?: IRedditResult;
|
||||
Error?: IError;
|
||||
}
|
18
src/index.ts
18
src/index.ts
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue