Skip to content

Fix issue where 404 errors are mistaken for server errors. #4534

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 19, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix issue where 404 errors are mistaken for server errors.
  • Loading branch information
GirlBossRush committed Nov 19, 2021
commit f15bc63ed6b81ada6da30cb5d7adea66a0593993
36 changes: 29 additions & 7 deletions src/node/routes/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,36 @@ import { rootPath } from "../constants"
import { replaceTemplates } from "../http"
import { escapeHtml, getMediaMime } from "../util"

const notFoundCodes = ["ENOENT", "EISDIR"]
interface ErrorWithStatusCode {
statusCode: number
}

interface ErrorWithCode {
code: string
}

/** Error is network related. */
export const errorHasStatusCode = (error: any): error is ErrorWithStatusCode => {
return error && "statusCode" in error
}

/** Error originates from file system. */
export const errorHasCode = (error: any): error is ErrorWithCode => {
return error && "code" in error
}

const notFoundCodes = [404, "ENOENT", "EISDIR"]

export const errorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
if (notFoundCodes.includes(err.code)) {
err.status = HttpCode.NotFound
let statusCode = 500

if (errorHasStatusCode(err)) {
statusCode = err.statusCode
} else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {
statusCode = HttpCode.NotFound
}

const status = err.status ?? err.statusCode ?? 500
res.status(status)
res.status(statusCode)

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