'Express middleware not catching errors
With using express and typescript I'm trying to create an middleware to catch errors like eq. Sentry, code is below:
const catchError = (
error: Error,
req: Request,
_res: Response,
next: any
) => {
console.log("ERROR: ", error);
//some logic
next(error);
}
index.ts
app.use(bodyParser.json({ limit }));
app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));
app.use(express.json());
app.use(cors({ credentials: true, origin: true }));
app.use(bodyParser.urlencoded({ extended: false }));
//controllers
app.use(catchError as express.ErrorRequestHandler)
why my middleware is working only when i put:
} catch (error) {
next(error);
}
in function where is an error and not working without it? This middleware should also catching errors and exceptions without using next(error)
thanks for any help!
Solution 1:[1]
I think you need to add a method override to use that custom error handler.
const methodOverride = require('method-override')
app.use(bodyParser.json({ limit }));
app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));
app.use(express.json());
app.use(cors({ credentials: true, origin: true }));
app.use(bodyParser.urlencoded({ extended: false }));
// Try to use this to override the custom error handler
app.use(methodOverride())
app.use(catchError as express.ErrorRequestHandler)
Reference:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | taipei |