Skip to content

Commit 0b906f7

Browse files
add 500 error email middleware (#273)
2 parents 5c523d1 + 520508b commit 0b906f7

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

apps/web/backend/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const express = require('express');
22
const connectToMongo = require('./db');
33
const cors = require('cors');
4+
const handleError = require('./middleware/error');
45

56
const load = async () => {
67
await connectToMongo();
@@ -10,6 +11,7 @@ const load = async () => {
1011

1112
app.use(express.json());
1213
app.use(cors());
14+
1315

1416
// Available Routes
1517
app.use('/api/auth', require('./routes/auth'));
@@ -20,6 +22,9 @@ const load = async () => {
2022
res.send('Hi!');
2123
});
2224

25+
// Error handling middleware
26+
app.use(handleError);
27+
2328
app.listen(PORT, () => {
2429
console.log(`The App is running at http://localhost:${PORT}`);
2530
});

apps/web/backend/middleware/error.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const nodemailer = require('nodemailer');
2+
const outlookEmail = process.env.outlookEmail;
3+
const outlookPassword = process.env.outlookPassword;
4+
5+
const handleError = (err, req, res, next) => {
6+
console.error(err.stack);
7+
const statusCode = err.statusCode || 500;
8+
const message = err.message || 'Internal Server Error';
9+
10+
console.log("Send message")
11+
12+
if (statusCode === 500) {
13+
const transporter = nodemailer.createTransport({
14+
service: 'hotmail',
15+
auth: {
16+
user: outlookEmail,
17+
pass: outlookPassword
18+
}
19+
});
20+
21+
const mailOptions = {
22+
from: outlookEmail,
23+
to: outlookEmail,
24+
subject: `Important!! : ${message}`,
25+
text: `Stack Trace:\n${err.stack}`
26+
};
27+
28+
transporter.sendMail(mailOptions, (error, info) => {
29+
if (error) {
30+
console.error(error);
31+
} else {
32+
console.log(`Email sent: ${info.response}`);
33+
}
34+
});
35+
}
36+
res.status(statusCode).send(message);
37+
}
38+
39+
module.exports = handleError;

0 commit comments

Comments
 (0)