Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Error Handleing. Modified Country API using new error hand… #173

Draft
wants to merge 2 commits into
base: development
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions src/AppError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
export class AppError extends Error {
public readonly name: string
public readonly httpCode: number
public readonly isOperational: boolean
public readonly details?: Record<string, any>

constructor(
name: string = AppErrorTypes.INTERNAL_SERVER_ERROR,
message: string = AppErrorDetails[AppErrorTypes.INTERNAL_SERVER_ERROR]
.message,
httpCode: number = AppErrorDetails[AppErrorTypes.INTERNAL_SERVER_ERROR]
.httpCode,
isOperational = true,
details?: Record<string, any>
) {
super(message)
Object.setPrototypeOf(this, new.target.prototype)
this.name = name
this.httpCode = httpCode
this.isOperational = isOperational
this.details = details
Error.captureStackTrace(this)
}
}

export function createAppError(
errorType: AppErrorTypes,
details?: Record<string, any>
): AppError {
const { message, httpCode } = AppErrorDetails[errorType]
return new AppError(errorType, message, httpCode, true, details)
}

export enum AppErrorTypes {
NOT_FOUND_ERROR = 'NOT_FOUND_ERROR',
MULTIPLE_RECORDS_FOUND_ERROR = 'MULTIPLE_RECORDS_FOUND_ERROR',
VALIDATION_ERROR = 'VALIDATION_ERROR',
AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR',
PERMISSION_DENIED_ERROR = 'PERMISSION_DENIED_ERROR',
INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR'
}

const AppErrorDetails: Record<
AppErrorTypes,
{ message: string; httpCode: number }
> = {
[AppErrorTypes.VALIDATION_ERROR]: {
message: 'Invalid input data',
httpCode: 400
},
[AppErrorTypes.AUTHENTICATION_ERROR]: {
message: 'Authentication failed',
httpCode: 401
},
[AppErrorTypes.NOT_FOUND_ERROR]: {
message: 'Resource not found',
httpCode: 404
},
[AppErrorTypes.INTERNAL_SERVER_ERROR]: {
message: 'An internal server error occurred',
httpCode: 500
},
[AppErrorTypes.PERMISSION_DENIED_ERROR]: {
message: 'Insufficient permission for this action',
httpCode: 403
},
[AppErrorTypes.MULTIPLE_RECORDS_FOUND_ERROR]: {
message: 'Multple records has been found',
httpCode: 400
}
}
30 changes: 30 additions & 0 deletions src/ErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { type Response } from 'express'
import { AppError } from './AppError'

class ErrorHandler {
public async handleError(error: Error, response: Response): Promise<void> {
console.error(error)
await this.sendErrorResponse(error, response)
}

private async sendErrorResponse(
error: Error,
response: Response
): Promise<void> {
if (error instanceof AppError) {
response.status(error.httpCode).json({
status: false,
message: error.message,
data: null
})
} else {
response.status(500).json({
status: false,
message: 'Something went wrong. Please contact administrator.',
data: null
})
}
}
}

export const errorHandler = new ErrorHandler()
7 changes: 6 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import cors from 'cors'
import type { Express } from 'express'
import type { Express, NextFunction, Request, Response } from 'express'
import express from 'express'
import fs from 'fs'
import passport from 'passport'
Expand All @@ -18,6 +18,7 @@ import mentorRouter from './routes/mentor/mentor.route'
import profileRouter from './routes/profile/profile.route'
import path from 'path'
import countryRouter from './routes/country/country.route'
import { errorHandler } from './ErrorHandler'

const app = express()
const staticFolder = 'uploads'
Expand Down Expand Up @@ -48,6 +49,10 @@ app.use('/api/categories', categoryRouter)
app.use('/api/emails', emailRouter)
app.use('/api/countries', countryRouter)

app.use(async (err: Error, req: Request, res: Response, next: NextFunction) => {
await errorHandler.handleError(err, res)
})

if (!fs.existsSync(staticFolder)) {
fs.mkdirSync(staticFolder, { recursive: true })
console.log('Directory created successfully!')
Expand Down
27 changes: 11 additions & 16 deletions src/controllers/country.controller.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
import type { Request, Response } from 'express'
import type { ApiResponse } from '../types'
import type Country from '../entities/country.entity'
import { getAllCountries } from '../services/country.service'
import { getAllCountries, getCountryById } from '../services/country.service'

export const getCountries = async (
req: Request,
res: Response
): Promise<ApiResponse<Country[]>> => {
try {
const data = await getAllCountries()
if (!data) {
return res.status(404).json({ message: 'Countries Not Found' })
}
return res.status(200).json({ data, message: 'Countries Found' })
} catch (err) {
if (err instanceof Error) {
console.error('Error executing query', err)
return res
.status(500)
.json({ error: 'Internal server error', message: err.message })
}
throw err
}
const data = await getAllCountries()
return res.status(200).json({ data, message: 'Countries Found' })
}

export const getCountryWithId = async (
req: Request,
res: Response
): Promise<ApiResponse<Country[]>> => {
const data = await getCountryById(req.params.id)
return res.status(200).json({ data, message: 'Country Details' })
}
9 changes: 7 additions & 2 deletions src/routes/country/country.route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import express from 'express'
import { getCountries } from '../../controllers/country.controller'
import {
getCountries,
getCountryWithId
} from '../../controllers/country.controller'
import { asyncHandler } from '../../utils'

const countryRouter = express.Router()

countryRouter.get('/', getCountries)
countryRouter.get('/', asyncHandler(getCountries))
countryRouter.get('/:id', asyncHandler(getCountryWithId))

export default countryRouter
18 changes: 15 additions & 3 deletions src/services/country.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
import { AppErrorTypes, createAppError } from '../AppError'
import { dataSource } from '../configs/dbConfig'
import Country from '../entities/country.entity'

export const getAllCountries = async (): Promise<Country[] | null> => {
export const getAllCountries = async (): Promise<Country[]> => {
const countryRepository = dataSource.getRepository(Country)
const countries: Country[] = await countryRepository.find({
const countries = await countryRepository.find({
select: ['uuid', 'code', 'name']
})
if (countries && countries.length > 0) {
return countries
}
return null
throw createAppError(AppErrorTypes.NOT_FOUND_ERROR)
}

export const getCountryById = async (id: string): Promise<Country> => {
const countryRepository = dataSource.getRepository(Country)
const country = await countryRepository.findOneBy({
uuid: id
})
if (country) {
return country
}
throw createAppError(AppErrorTypes.NOT_FOUND_ERROR)
}
15 changes: 14 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { JWT_SECRET, CLIENT_URL } from './configs/envConfig'
import jwt from 'jsonwebtoken'
import type { Response } from 'express'
import type { NextFunction, Request, Response } from 'express'
import type Mentor from './entities/mentor.entity'
import path from 'path'
import multer from 'multer'
Expand All @@ -11,6 +11,7 @@ import { randomUUID } from 'crypto'
import { certificatesDir } from './app'
import type Mentee from './entities/mentee.entity'
import { type ZodError } from 'zod'
import { type ApiResponse } from './types'

export const signAndSetCookie = (res: Response, uuid: string): void => {
const token = jwt.sign({ userId: uuid }, JWT_SECRET ?? '')
Expand Down Expand Up @@ -299,3 +300,15 @@ export const formatValidationErrors = (
message: `${issue.path.join('.')} is ${issue.message}`
}))
}

export const asyncHandler =
(
fn: (
req: Request,
res: Response,
next: NextFunction
) => Promise<ApiResponse<any>>
) =>
(req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next)
}