fix: error handling

- Remove unnecessary try-catch block in createSession function
- Add error handling for missing session ID in socket.js
- Improve error handling in connectDB function
- Add error handling middleware for server errors
- Add default export for get function in env.js

Signed-off-by: wancat <wancat@wancat.cc>
This commit is contained in:
wancat committed 2023-07-25 15:46:59 +08:00
1 parent 943c11714c
commit 88ed447573
6 files changed
+36 -14

No files matched your search

@@ -22,13 +22,13 @@ export async function createSession(req, res) {
return
}
const newSession = new Session({
user: req.user,
quest,
containerId: `quest-${quest.id}-${req.user.username}-${Date.now()}`,
})
try {
const newSession = new Session({
user: req.user,
quest,
containerId: `quest-${quest.id}-${req.user.username}-${Date.now()}`,
})
const session = await newSession.save()
res.status(201).json(session)
} catch (err) {
+19 -7
View File
@@ -21,13 +21,25 @@ export default (server) => {
io.on('connection', async (socket) => {
console.log('Connected to the client.')
const session = await Session.findOne({
_id: socket.handshake.query.session_id,
user: socket.user,
})
if (!session) {
socket.send('Session not found.')
const sessionId = socket.handshake.query.session_id
if (!sessionId) {
socket.send('Session ID not found.')
socket.disconnect()
return
}
let session
try {
session = await Session.findOne({
_id: sessionId,
user: socket.user,
})
if (!session) {
socket.send('Session not found.')
socket.disconnect()
return
}
} catch (err) {
socket.send(err.message)
socket.disconnect()
return
}
+2 -1
View File
@@ -6,6 +6,7 @@ export default async function connectDB() {
await mongoose.connect(config.db)
console.log('Connected to MongoDB')
} catch (err) {
console.log(err)
console.error(err)
process.exit(1)
}
}
+3
View File
@@ -9,6 +9,7 @@ import connectDB from './db.js'
import apiRouter from './api/routes/index.js'
import loadAndUpdateQuests from './utils/quest.js'
import config from './config.js'
import errorHandler from './middleware/error.js'
async function main() {
const app = express()
@@ -28,6 +29,8 @@ async function main() {
app.use('/api/v1', apiRouter)
app.use(errorHandler)
server.listen(config.port, config.host, () => {
console.log(`Server listening at http://${config.host}:${config.port}`)
})
+5
View File
@@ -0,0 +1,5 @@
// eslint-disable-next-line no-unused-vars
export default function errorHandler(err, req, res, next) {
console.error(err.stack) // Log error stack trace to the console
res.status(500).send({ message: err.message }) // Send error response
}
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable import/prefer-default-export */
export function get(key, defaultValue) {
const value = process.env[key]
if (value != null) {