Skip to content

Commit 3b646da

Browse files
committed
error controller created
1 parent 3aeb0e3 commit 3b646da

File tree

3 files changed

+25
-4
lines changed

3 files changed

+25
-4
lines changed

Backend/app.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ const express = require('express');
33

44
const morgan = require('morgan');
55
const plantRouter = require('./routes/plantRoutes');
6+
const AppError = require('./utils/appError');
7+
const globalErrorHandler = require('./controllers/errorController');
68

79
const app = express();
810

@@ -13,12 +15,11 @@ app.use(express.json());
1315
app.use('/api/plants', plantRouter);
1416

1517
app.all('*', (req, res, next) => {
16-
res.status(404).json({
17-
status: 'fail',
18-
message: `Can't find ${req.originalUrl} on this server`,
19-
});
18+
next(new AppError(`Can't find ${req.originalUrl} on this server`, 404));
2019
});
2120

21+
app.use(globalErrorHandler);
22+
2223
// const userRouter = express.Router();
2324
// app.use('/api/user', userRouter);
2425

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = (err, req, res, next) => {
2+
err.statusCode = err.statusCode || 500;
3+
err.status = err.status || 'error';
4+
res.status(err.statusCode).json({
5+
status: err.status,
6+
message: err.message,
7+
});
8+
};

Backend/utils/appError.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class AppError extends Error {
2+
constructor(message, statusCode) {
3+
super(message);
4+
this.statusCode = statusCode;
5+
this.status = `${statusCode}`.startsWith('4') ? `fail` : `error`;
6+
this.isOperational = true;
7+
8+
Error.captureStackTrace(this, this.constructor);
9+
}
10+
}
11+
12+
module.exports = AppError;

0 commit comments

Comments
 (0)