Skip to content

Commit

Permalink
Normalize image optimizer error status codes (#34699)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Feb 23, 2022
1 parent b3f2b38 commit 99ee222
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
8 changes: 7 additions & 1 deletion packages/next/server/image-optimizer.ts
Expand Up @@ -259,7 +259,13 @@ export class ImageError extends Error {

constructor(statusCode: number, message: string) {
super(message)
this.statusCode = statusCode

// ensure an error status is used > 400
if (statusCode >= 400) {
this.statusCode = statusCode
} else {
this.statusCode = 500
}
}
}

Expand Down
23 changes: 21 additions & 2 deletions test/integration/image-optimizer/test/util.js
Expand Up @@ -25,11 +25,17 @@ export async function serveSlowImage() {
const server = http.createServer(async (req, res) => {
const parsedUrl = new URL(req.url, 'http://localhost')
const delay = Number(parsedUrl.searchParams.get('delay')) || 500
const status = Number(parsedUrl.searchParams.get('status')) || 200

console.log('delay image for', delay)
console.log('delaying image for', delay)
await waitFor(delay)

res.statusCode = 200
res.statusCode = status

if (status === 308) {
res.end('invalid status')
return
}
res.setHeader('content-type', 'image/png')
res.end(await fs.readFile(join(__dirname, '../app/public/test.png')))
})
Expand Down Expand Up @@ -127,6 +133,19 @@ export function runTests(ctx) {
slowImageServer.stop()
})

if (ctx.domains.includes('localhost')) {
it('should normalize invalid status codes', async () => {
const url = `http://localhost:${
slowImageServer.port
}/slow.png?delay=${1}&status=308`
const query = { url, w: ctx.w, q: 39 }
const opts = { headers: { accept: 'image/webp' }, redirect: 'manual' }

const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(500)
})
}

it('should return home page', async () => {
const res = await fetchViaHTTP(ctx.appPort, '/', null, {})
expect(await res.text()).toMatch(/Image Optimizer Home/m)
Expand Down

0 comments on commit 99ee222

Please sign in to comment.