Skip to content

Commit 3a7c315

Browse files
committed
fix: improve error handling in ErrorHandler for API responses
1 parent 3d0f35f commit 3a7c315

File tree

2 files changed

+8
-9
lines changed

2 files changed

+8
-9
lines changed

express/src/core/utils/request-handlers.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,10 @@ export const ErrorHandler = (
7272
writeFileSync(path.join(logsDir, 'error.log'), logContent + newLogEntry, 'utf-8')
7373
}
7474

75-
res.statusMessage = error.message
76-
7775
// If the request is an API call, return a JSON response. Otherwise, you might want to render an error page.
7876
const headers = req instanceof ServerResponse ? req.getHeaders() : req.headers
77+
const acceptsHeader = Array.isArray(headers.accept) ? headers.accept.join(',') : headers.accept ?? ''
78+
const expectsJson = acceptsHeader.includes('application/json') || req.originalUrl.startsWith('/api/')
7979

8080
if (!(err instanceof ValidationException) || Number(error.code) === 404) {
8181
delete error.errors
@@ -84,7 +84,7 @@ export const ErrorHandler = (
8484

8585
if (process.env.NODE_ENV === 'development') console.error(error)
8686

87-
if (headers.accept?.includes('application/json')) {
87+
if (expectsJson) {
8888
return res.status(error.code).json(error)
8989
} else {
9090
return res.status(error.code).setHeader('Content-Type', 'text/html').send(buildHtmlErrorResponse({

h3/src/core/utils/request-handlers.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ export const ErrorHandler = (err: HTTPError, event: H3Event) => {
2727
message: typeof err === 'string' ? `${message}: ${err}` : err.message || message,
2828
}
2929

30-
event.res.status = error.code
31-
event.res.statusText = error.message
30+
event.res.status = error.code < 100 || error.code >= 600 ? 500 : error.code
3231

3332
if (typeof err !== 'string' && err.stack) {
3433
const [stack, ...rest] = err.stack.split('\n')
@@ -75,10 +74,10 @@ export const ErrorHandler = (err: HTTPError, event: H3Event) => {
7574
if (process.env.NODE_ENV === 'development') console.error(error)
7675

7776
// If the request is an API call, return a JSON response. Otherwise, you might want to render an error page.
78-
if (
79-
event.req.headers.get('accept')?.includes('application/json') ||
80-
event.req._url?.pathname?.startsWith('/api')
81-
) {
77+
const acceptsHeader = event.req.headers.get('accept') ?? ''
78+
const expectsJson = acceptsHeader.includes('application/json') || event.req._url?.pathname?.startsWith('/api')
79+
80+
if (expectsJson) {
8281
return {
8382
...error,
8483
error: true,

0 commit comments

Comments
 (0)