I have the following code to check the origin header and allow access, using express and the npm cors plugin
const app = express();
const cors = require('cors')
var corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
Now I wonder if there is way to catch the "new Error" callback?
And send back a 400 http status?
Thanks!
Yes, this is explained in the Express docs under Error Handling.
Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
If you pass an error to
next()
and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.
The docs don't go into that much more detail on the default handler, but after looking at the source code, the default handler is a separate module called finalhandler
.
Anyways, to override this handler, refer to the section in the Express docs titled Writing error handlers.
It explains:
Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three:
(err, req, res, next)
. For example:app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') })
You define error-handling middleware last, after other
app.use()
and routes calls
So in your case, if you wanted to respond with a 400, you might write something like this:
const app = express();
const cors = require('cors')
var corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
// This overrides the default error handler, and must be called _last_ on the app
app.use(function customErrorHandler(err, req, res, next) {
res.status(400).send('Your custom error message here');
});
Express also includes a sample server in its repo, showing this erorr handling override.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With