Skip to content

Commit eec1738

Browse files
committed
errors changed to new error Classes
1 parent b3f55ee commit eec1738

File tree

7 files changed

+256
-202
lines changed

7 files changed

+256
-202
lines changed

README.md

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
This project is a web application developed using Node.js v16.20.1. It follows the Model-View-Controller (MVC) architectural pattern, providing a structured and modular approach to building web applications.
1010

1111
# THIS DOCUMENTATION IS NOT FINISHED AT THE MOMENT
12+
1213
## Development Environment Setup
1314

1415
To set up the development environment for this project, follow these steps:
16+
1517
- [Docker File](https://hub.docker.com/repository/docker/clamshell6412/ecomerce_res_api/general) (production only)
1618
- Install Node.js v16.20.1 (or a compatible version) on your system.
1719
- Clone the project repository from [repository URL].
@@ -42,12 +44,12 @@ STRIPE_TOKEN=sk_text_z&&2DbCJa9d3gZkxFwJdE$&hHbRe47KHxAF%&N#qRVx*zVFG$W
4244

4345
### User
4446

45-
| User Actions | Routes | Required | Http Verb |
46-
| --------------- | ------------------------- | ------------------------- | --------- |
47-
| Sign In | `/api/users/signIn` | email, username, password | Post |
48-
| Sign Up | `/api/users/signUp` | email, password | Post |
49-
| User Stats | `/api/users/stats` | must by Admin | Get |
50-
| Find user by Id | `/api/users/find/:userId` | userId | Get |
47+
| User Actions | Routes | Required | Http Verb |
48+
| --------------- | ------------------------- | -------------------------- | --------- |
49+
| Sign In | `/api/users/signIn` | email , password | Post |
50+
| Sign Up | `/api/users/signUp` | email, password , password | Post |
51+
| User Stats | `/api/users/stats` | must by Admin | Get |
52+
| Find user by Id | `/api/users/find/:userId` | userId | Get |
5153

5254
[Postman Documentation]()
5355

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import cart from './server/Routes/shoppingCartRoutes.js';
77
import product from './server/Routes/productRoutes.js';
88
import purchase from './server/Routes/purchasesRoutes.js';
99
import comment from './server/Routes/commentsRoutes.js';
10-
import errorHandler from './server/helpers/errorHandler.js';
10+
import { errorHandler } from './server/helpers/errorHandler.js';
1111

1212
//config
1313

package-lock.json

Lines changed: 184 additions & 177 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/View/productView.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Product from '../Models/productModel.js';
22
import mongoose from 'mongoose';
3+
import { NotFoundError } from '../helpers/errorHandler.js';
34

45
const productService = {
56
getProduct,
@@ -25,7 +26,7 @@ async function getProductById(productId) {
2526
const product = await Product.findById(productId);
2627
return product;
2728
} else {
28-
throw new Error('not found');
29+
throw new NotFoundError('Product Not found');
2930
}
3031
}
3132

server/View/usersViews.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ import Encrypt from '../helpers/bcrypt.js';
22
import User from '../Models/userModel.js';
33
import { JWT_TOKEN } from '../../index.js';
44
import Token from '../helpers/token.js';
5+
import {
6+
BadRequestError,
7+
NotFoundError,
8+
UnauthorizedError,
9+
} from '../helpers/errorHandler.js';
510

611
//config
712
const userService = {
@@ -35,7 +40,7 @@ async function signIn(user) {
3540
existingUser.password,
3641
);
3742
if (!isPasswordMatch) {
38-
throw new Error('wrong credentials');
43+
throw new UnauthorizedError('wrong credentials');
3944
} else {
4045
const userId = existingUser._id.toString();
4146
const token = await jwt.generateToken(userId, JWT_TOKEN, {
@@ -46,6 +51,14 @@ async function signIn(user) {
4651
}
4752
}
4853

54+
async function checkLength(item, num) {
55+
if (item.lenght >= num) {
56+
return true;
57+
} else {
58+
throw new BadRequestError(`the minimum allowed is ${num}`);
59+
}
60+
}
61+
4962
async function signUp(user) {
5063
const allowedFields = ['email', 'password', 'username'];
5164

@@ -57,13 +70,14 @@ async function signUp(user) {
5770
}, {});
5871

5972
const registeredUser = await findByEmail(filteredUser.email);
60-
if (!registeredUser) {
73+
const validatePass = await checkLength(filteredUser.password, 8);
74+
if (!registeredUser && validatePass) {
6175
const encryptPassword = await encrypt.hashPassword(filteredUser.password);
6276
const createUser = new User({ ...filteredUser, password: encryptPassword });
6377
const newUser = await createUser.save();
6478
return newUser;
6579
} else {
66-
throw new Error('bad request');
80+
throw new BadRequestError('email already in use');
6781
}
6882
}
6983

@@ -72,7 +86,7 @@ async function getUser(userId) {
7286
if (user) {
7387
return user;
7488
} else {
75-
throw new Error('not found');
89+
throw new NotFoundError('User Not found');
7690
}
7791
}
7892

server/helpers/adminCheck.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import User from '../Models/userModel.js';
2+
import { UnauthorizedError } from './errorHandler.js';
23

34
async function adminCheck(req, res, next) {
45
const user = await User.findById(req.user.id);
56
if (user.isAdmin) {
67
next();
78
} else {
8-
next(new Error('unauthorized'));
9+
next(new UnauthorizedError('You are Unauthorized'));
910
}
1011
}
1112

server/helpers/errorHandler.js

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,45 @@
1+
class NotFoundError extends Error {
2+
constructor(message) {
3+
super(message);
4+
this.name = 'NotFoundError';
5+
this.statusCode = 404;
6+
}
7+
}
8+
9+
class AuthenticationError extends Error {
10+
constructor(message) {
11+
super(message);
12+
this.name = 'AuthenticationError';
13+
this.statusCode = 401;
14+
}
15+
}
16+
17+
class UnauthorizedError extends Error {
18+
constructor(message) {
19+
super(message);
20+
this.name = 'UnauthorizedError';
21+
this.statusCode = 403;
22+
}
23+
}
24+
class BadRequestError extends Error {
25+
constructor(message) {
26+
super(message);
27+
this.name = 'BadRequestError';
28+
this.statusCode = 400;
29+
}
30+
}
31+
132
function errorHandler(error, req, res, next) {
2-
if (error.message === 'bad request') {
3-
res.status(400).json({ error: 'Bad Request' });
4-
} else if (error.message === 'wrong credentials') {
5-
res.status(401).json({ error: 'Wrong Credentials' });
6-
} else if (error.message === 'unauthorized') {
7-
res.status(403).json({ error: 'Unauthorized' });
8-
} else if (error.message === 'not found') {
9-
res.status(404).json({ error: 'Not Found' });
10-
} else if (error.message === 'stripe went wrong') {
11-
res.status(500).json({ error: 'Payment went wrong' });
33+
if (error.statusCode) {
34+
res.status(error.statusCode).json({ error: error.message });
1235
} else {
13-
next(error);
36+
res.status(500).json({ error: error.message });
1437
}
1538
}
16-
export default errorHandler;
39+
export {
40+
errorHandler,
41+
UnauthorizedError,
42+
BadRequestError,
43+
AuthenticationError,
44+
NotFoundError,
45+
};

0 commit comments

Comments
 (0)