Skip to content

Commit

Permalink
feat: 500+ error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Laplace-piedplat committed Dec 12, 2024
1 parent 0cac856 commit bdc64df
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
16 changes: 3 additions & 13 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,7 @@ import {
SuperAgentSerializer,
ApiRequestHooks,
} from './types.js'
import {
dumpRequest,
dumpRequestBody,
dumpRequestCookies,
dumpRequestHeaders,
stackToError,
} from './utils.js'
import { dumpRequest, dumpRequestBody, dumpRequestCookies, dumpRequestHeaders } from './utils.js'

const DUMP_CALLS = {
request: dumpRequest,
Expand Down Expand Up @@ -176,13 +170,9 @@ export class ApiRequest extends Macroable {
}

/**
* Raise exception when received 500 status code from the server
* For all HTTP errors (including 500+), return the error response
* This allows proper handling of server errors via ApiResponse
*/
if (error.response.status >= 500) {
await this.#setupRunner.cleanup(error, this)
throw stackToError(error.response.text)
}

response = error.response
}

Expand Down
32 changes: 24 additions & 8 deletions tests/response/error_handling.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,34 @@ test.group('Response | error handling', (group) => {
assert.equal(response.status(), 401)
})

test('raise fatal errors raised by the server', async ({ assert }) => {
test('returns ApiResponse for 500 errors', async ({ assert }) => {
httpServer.onRequest((_, res) => {
try {
throw new Error('Something went wrong')
} catch (error) {
res.statusCode = 500
res.end(error.stack)
}
res.statusCode = 500
res.end('Internal server error')
})

const request = new ApiRequest({ baseUrl: httpServer.baseUrl, method: 'GET', endpoint: '/' })
const response = await request

assert.equal(response.status(), 500)
assert.isTrue(response.hasFatalError())
assert.isTrue(response.hasServerError())
})

test('handles server errors with response body', async ({ assert }) => {
httpServer.onRequest((_, res) => {
res.statusCode = 500
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: 'Something went wrong', code: 'INTERNAL_ERROR' }))
})

const request = new ApiRequest({ baseUrl: httpServer.baseUrl, method: 'GET', endpoint: '/' })
const response = await request

await assert.rejects(() => request, 'Error: Something went wrong')
assert.equal(response.status(), 500)
assert.deepEqual(response.body(), {
error: 'Something went wrong',
code: 'INTERNAL_ERROR',
})
})
})

0 comments on commit bdc64df

Please sign in to comment.