Skip to content

Commit f15bc63

Browse files
committed
Fix issue where 404 errors are mistaken for server errors.
1 parent 3157a40 commit f15bc63

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/node/routes/errors.ts

+29-7
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,36 @@ import { rootPath } from "../constants"
88
import { replaceTemplates } from "../http"
99
import { escapeHtml, getMediaMime } from "../util"
1010

11-
const notFoundCodes = ["ENOENT", "EISDIR"]
11+
interface ErrorWithStatusCode {
12+
statusCode: number
13+
}
14+
15+
interface ErrorWithCode {
16+
code: string
17+
}
18+
19+
/** Error is network related. */
20+
export const errorHasStatusCode = (error: any): error is ErrorWithStatusCode => {
21+
return error && "statusCode" in error
22+
}
23+
24+
/** Error originates from file system. */
25+
export const errorHasCode = (error: any): error is ErrorWithCode => {
26+
return error && "code" in error
27+
}
28+
29+
const notFoundCodes = [404, "ENOENT", "EISDIR"]
30+
1231
export const errorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
13-
if (notFoundCodes.includes(err.code)) {
14-
err.status = HttpCode.NotFound
32+
let statusCode = 500
33+
34+
if (errorHasStatusCode(err)) {
35+
statusCode = err.statusCode
36+
} else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {
37+
statusCode = HttpCode.NotFound
1538
}
1639

17-
const status = err.status ?? err.statusCode ?? 500
18-
res.status(status)
40+
res.status(statusCode)
1941

2042
// Assume anything that explicitly accepts text/html is a user browsing a
2143
// page (as opposed to an xhr request). Don't use `req.accepts()` since
@@ -27,8 +49,8 @@ export const errorHandler: express.ErrorRequestHandler = async (err, req, res, n
2749
const content = await fs.readFile(resourcePath, "utf8")
2850
res.send(
2951
replaceTemplates(req, content)
30-
.replace(/{{ERROR_TITLE}}/g, status)
31-
.replace(/{{ERROR_HEADER}}/g, status)
52+
.replace(/{{ERROR_TITLE}}/g, statusCode.toString())
53+
.replace(/{{ERROR_HEADER}}/g, statusCode.toString())
3254
.replace(/{{ERROR_BODY}}/g, escapeHtml(err.message)),
3355
)
3456
} else {

0 commit comments

Comments
 (0)