Skip to content

Commit cb991a9

Browse files
committed
Handle errors for JSON requests
Previously it would have just given them the error HTML.
1 parent 3f1750c commit cb991a9

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

src/node/routes/index.ts

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -121,23 +121,29 @@ export const register = async (
121121
throw new HttpError("Not Found", HttpCode.NotFound)
122122
})
123123

124-
const errorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
125-
const resourcePath = path.resolve(rootPath, "src/browser/pages/error.html")
126-
res.set("Content-Type", getMediaMime(resourcePath))
127-
try {
124+
const errorHandler: express.ErrorRequestHandler = async (err, req, res) => {
125+
if (err.code === "ENOENT" || err.code === "EISDIR") {
126+
err.status = HttpCode.NotFound
127+
}
128+
129+
const status = err.status ?? err.statusCode ?? 500
130+
res.status(status)
131+
132+
if (req.accepts("application/json")) {
133+
res.json({
134+
error: err.message,
135+
...(err.details || {}),
136+
})
137+
} else {
138+
const resourcePath = path.resolve(rootPath, "src/browser/pages/error.html")
139+
res.set("Content-Type", getMediaMime(resourcePath))
128140
const content = await fs.readFile(resourcePath, "utf8")
129-
if (err.code === "ENOENT" || err.code === "EISDIR") {
130-
err.status = HttpCode.NotFound
131-
}
132-
const status = err.status ?? err.statusCode ?? 500
133-
res.status(status).send(
141+
res.send(
134142
replaceTemplates(req, content)
135143
.replace(/{{ERROR_TITLE}}/g, status)
136144
.replace(/{{ERROR_HEADER}}/g, status)
137145
.replace(/{{ERROR_BODY}}/g, err.message),
138146
)
139-
} catch (error) {
140-
next(error)
141147
}
142148
}
143149

0 commit comments

Comments
 (0)