Whenever I make a request and encounter an error, the error middleware is supposed to handle it. For example:
# routes.ts
// sending an error
router.get('/', (req, res) => {
throw new BadRequestError("test")
})
This triggers the errorMiddleware and processes the error successfully. However, when I trigger an error from the controller, like so:
# UserController.ts
export class UserController {
static async registerNewUser(req: Request, res: Response) {
const newUser = new User(req.body)
const alreadyExists = await User.findUser(newUser)
if (alreadyExists) {
throw new BadRequestError("test")
}
}
}
And then route it accordingly:
# routes.ts
router.post('/register', UserController.registerNewUser)
The middleware doesn't get called and the application crashes. Here's a snippet of my app.ts code:
# app.ts
const app = express()
app.use(express.json());
app.use(router)
app.use(errorMiddleware)
export { app }
This is what my server.ts code looks like:
# server.ts
import { app } from "./app";
const PORT = process.env.PORT
app.listen (PORT, () => console.log(`Server is running on port ${PORT}`))
I've experimented with changing the error middleware and adding additional ones, but nothing seems to work. I also attempted to remove errors from subclasses and pass them directly to controllers, but faced the same issue.
I hope to be able to send and manage errors from any class within my API using the designated middleware.