Handle errors for JSON requests

Previously it would have just given them the error HTML.
This commit is contained in:
Asher 2020-11-05 15:19:15 -06:00
parent 3f1750cf83
commit cb991a9143
No known key found for this signature in database
GPG Key ID: D63C1EF81242354A
1 changed files with 17 additions and 11 deletions

View File

@ -121,23 +121,29 @@ export const register = async (
throw new HttpError("Not Found", HttpCode.NotFound) throw new HttpError("Not Found", HttpCode.NotFound)
}) })
const errorHandler: express.ErrorRequestHandler = async (err, req, res, next) => { const errorHandler: express.ErrorRequestHandler = async (err, req, res) => {
const resourcePath = path.resolve(rootPath, "src/browser/pages/error.html")
res.set("Content-Type", getMediaMime(resourcePath))
try {
const content = await fs.readFile(resourcePath, "utf8")
if (err.code === "ENOENT" || err.code === "EISDIR") { if (err.code === "ENOENT" || err.code === "EISDIR") {
err.status = HttpCode.NotFound err.status = HttpCode.NotFound
} }
const status = err.status ?? err.statusCode ?? 500 const status = err.status ?? err.statusCode ?? 500
res.status(status).send( res.status(status)
if (req.accepts("application/json")) {
res.json({
error: err.message,
...(err.details || {}),
})
} else {
const resourcePath = path.resolve(rootPath, "src/browser/pages/error.html")
res.set("Content-Type", getMediaMime(resourcePath))
const content = await fs.readFile(resourcePath, "utf8")
res.send(
replaceTemplates(req, content) replaceTemplates(req, content)
.replace(/{{ERROR_TITLE}}/g, status) .replace(/{{ERROR_TITLE}}/g, status)
.replace(/{{ERROR_HEADER}}/g, status) .replace(/{{ERROR_HEADER}}/g, status)
.replace(/{{ERROR_BODY}}/g, err.message), .replace(/{{ERROR_BODY}}/g, err.message),
) )
} catch (error) {
next(error)
} }
} }