Skip to content

Commit

Permalink
Added proper error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
rosemdev committed Feb 20, 2024
1 parent 476fece commit 2eca9cb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
9 changes: 9 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');

const feedRoutes = require('./routes/feed');

const app = express();

// app.use(bodyParser.urlencoded()); // x-www-form-urlencoded <form>
app.use(bodyParser.json()); // application/json
app.use('/images', express.static(path.join(__dirname, 'images')));

app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
Expand All @@ -20,6 +22,13 @@ app.use((req, res, next) => {
});

app.use('/feed', feedRoutes);
app.use((error, req, res, next) => {
console.log(error);
const status = error.statusCode || 500;
const message = error.message;

res.status(status).json({ message: message });
});

mongoose
.connect(process.env.DB_CONNECTION_STRING)
Expand Down
18 changes: 12 additions & 6 deletions controllers/feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ exports.getPosts = (req, res, next) => {
};

exports.createPost = (req, res, next) => {
const errors = validationResult(req);
const errors = validationResult(req);

if (!errors.isEmpty()) {
return res
.status(422)
.json({ message: 'Validation Failed!', errors: errors.array() });
const error = new Error('Validation Failed!');
error.statusCode = 422;

throw error;
}
const title = req.body.title;
const content = req.body.content;
Expand All @@ -38,13 +39,18 @@ exports.createPost = (req, res, next) => {
},
});

return post
return post
.save()
.then((post) => {
res.status(201).json({
message: 'Post created successfully!',
post: post,
});
})
.catch((err) => next(new Error(err)));
.catch((err) => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};

0 comments on commit 2eca9cb

Please sign in to comment.