Add dinosaur API error handler
This commit is contained in:
parent
f432aa7d87
commit
60cabb3bcb
@ -1,9 +1,12 @@
|
||||
import express from "express";
|
||||
import { dinosaurRouter } from "./routes/dinosaurRoutes.js";
|
||||
import { errorHandler } from "./validation/errorHandler.js";
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(express.json());
|
||||
app.use(dinosaurRouter);
|
||||
// Error middleware must be registered after routes so it can handle rejected route handlers.
|
||||
app.use(errorHandler);
|
||||
|
||||
export { app };
|
||||
|
||||
17
lecture_5/dinosaurs/src/validation/errorHandler.js
Normal file
17
lecture_5/dinosaurs/src/validation/errorHandler.js
Normal file
@ -0,0 +1,17 @@
|
||||
import { ZodError } from "zod";
|
||||
|
||||
// Centralized Express error middleware for validation and unexpected runtime errors.
|
||||
export const errorHandler = (error, _request, response, _next) => {
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof ZodError) {
|
||||
return response.status(400).json({
|
||||
message: "Validation error",
|
||||
errors: error.issues,
|
||||
});
|
||||
}
|
||||
|
||||
return response.status(500).json({
|
||||
message: "Internal server error",
|
||||
});
|
||||
};
|
||||
Loading…
Reference in New Issue
Block a user