Skip to content
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
4 changes: 2 additions & 2 deletions src/controllers/user.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from 'express'

import UserService from '../services/user'
import { NotFoundError, BadRequestError } from '../helpers/apiError'
import { NotFoundError, BadRequestError, CustomError } from '../helpers/apiError'
import { AuthRequest } from '../types'

export const googleLogin = async (req: Request, res: Response, next: NextFunction) => {
Expand Down Expand Up @@ -38,7 +38,7 @@ export const findUserById = async (req: Request, res: Response, next: NextFuncti
const { userId } = req.params
return res.json(await UserService.findUserById(userId))
} catch (error) {
next(new NotFoundError('User not found', error))
next(new CustomError(res, error.status, error.message).sendError)
}
}

Expand Down
18 changes: 18 additions & 0 deletions src/helpers/apiError.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Response } from 'express'

export default class ApiError extends Error {
constructor(readonly statusCode: number, readonly message: string, readonly source?: Error) {
super()
Expand Down Expand Up @@ -33,3 +35,19 @@ export class BadRequestError extends ApiError {
super(400, message, source)
}
}

export class CustomError {
constructor(readonly res: Response, readonly statusCode: number, readonly message: string) {
this.res = res
this.statusCode = statusCode
this.message = message
}

get sendError() {
return this.returnError()
}
// Method
returnError() {
return this.res.json({ status: this.statusCode, message: this.message })
}
}
2 changes: 1 addition & 1 deletion src/routers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const router = express.Router()
router.get('/', findAllUsers)
router.get('/count', getUserCount)
router.get('/verify-token', isAuthenticated, getTokenInfo)
router.get('/:userId', isAuthenticated, isOwner, findUserById)
router.get('/:userId', findUserById)
router.get('/:userId/public', isAuthenticated, findPublicUserInfo)
router.post('/google-authenticate', googleLogin)
router.put('/:userId', isAuthenticated, updateUser)
Expand Down
4 changes: 2 additions & 2 deletions src/services/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ const findUserById = async (userId: string) => {
}
} catch (error) {
if (error.status) {
return error
throw error
} else {
return { status: 500, message: 'Bad Request', error: error }
throw { status: 500, message: 'Bad Request', error: error }
}
}
}
Expand Down