Skip to content

Commit

Permalink
Add error middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Dcrammer777 committed Oct 23, 2023
1 parent cd8f6b1 commit 7c1bfde
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 9 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@babel/preset-env": "^7.23.2",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"mysql2": "^3.6.2",
"nodemon": "^3.0.1",
"rimraf": "^5.0.5",
Expand Down
5 changes: 5 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ app.use("/", baseRoutes)
app.use("/user", userRoutes)
app.use("/test", testRoutes)

app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).json({ status: false, message: err.message })
})

app.listen(PORT, async () => {
console.log(`App listening at port ${PORT}`)
try {
Expand Down
25 changes: 16 additions & 9 deletions src/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
import express from "express"
import logMiddleware from "../middleware/logMiddleware"
import ash from "express-async-handler"
import { User } from "../database/User"

const router = express.Router()

router.use(logMiddleware)

router.get("/", async (req, res) => {
const users = await User.findAll()
res.json({ status: "success", data: users })
})
router.get(
"/",
ash(async (req, res) => {
const users = await User.findAll()
res.json({ status: "success", data: users })
})
)

router.post("/", async (req, res) => {
const { username, email, password } = req.body
const user = await User.create({ username, email, password })
res.json({ status: "success", data: user })
})
router.post(
"/",
ash(async (req, res) => {
const { username, email, password } = req.body
const user = await User.create({ username, email, password })
res.json({ status: "success", data: user })
})
)

const userRoutes = router
export default userRoutes

0 comments on commit 7c1bfde

Please sign in to comment.