I am working on a express(4.16.3) web server.
The page would do some special things according to the browser's language setting.
However, if the browser (for instance, some server bots) does NOT have an Accept-Language header, it would bring a 500 error.
Here is the original version:
//index.js - original - would return a 500 Internal Server Error
utils.catchAsyncErrors(async (req, res) => {
let lang = req.params.lang
if (!lang) {
const langs = accepts(req).languages()
try {
lang = langs[0].split('-')[0].toLowerCase()
} catch (err) {}
}
Here is the modified version - I use try...catch block but it fails to bypass the error.
//index.js - original - would still return a 500 Internal Server Error
utils.catchAsyncErrors(async (req, res) => {
let lang = req.params.lang
if (!lang) {
var langs;
try {
langs = accepts(req).languages();
} catch (err) {
langs = 'en';
}
try {
lang = langs[0].split('-')[0].toLowerCase()
} catch (err) {
lang = 'en';
}
}
If I comment out the entire logic about the language header check, it works.
//index.js - original - would work fine
utils.catchAsyncErrors(async (req, res) => {
let lang = req.params.lang
if (!lang) {
/*
var langs;
try {
langs = accepts(req).languages();
} catch (err) {
langs = 'en';
}
// const langs = accepts(req).languages()
try {
lang = langs[0].split('-')[0].toLowerCase()
} catch (err) {
lang = 'en';
}
*/
lang = 'en';
}
Just FYI, the other function mentioned in my code.
//utils.js - the catchAsyncErrors definition
exports.catchAsyncErrors = function (fn) {
return (req, res, next) => {
const routePromise = fn(req, res, next)
if (routePromise.catch) {
routePromise.catch(err => next(err))
}
}
}
What should I do to make the server work fine while it can both:
- Check the
Accept-Languageheader. - Not failing when there's no
Accept-Languageheader presented.