← All tasksNode.js · Junior
HttpError and a safe response
Write a class HttpError (extends Error, has status and message) and a function toResponse(error) for the server's error handler. It returns { status, body: { error } }.
For client errors (HttpError with a 4xx status) the message is shown as is. Everything else - a 5xx HttpError, plain Errors, even thrown strings or null - gives { error: "Internal Server Error" }: a 5xx status is kept, and anything that isn't an HttpError gets 500. The client must not see internal details such as database addresses.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (5)
const e = new HttpError(404, 'User not found'); expect(e).toBeInstanceOf(Error); expect(e).toBeInstanceOf(HttpError); expect(e.status).toBe(404); expect(e.message).toBe('User not found');
expect(toResponse(new HttpError(404, 'User not found'))).toEqual({ status: 404, body: { error: 'User not found' } }); expect(toResponse(new HttpError(422, 'Email is invalid'))).toEqual({ status: 422, body: { error: 'Email is invalid' } });
expect(toResponse(new Error('connect ECONNREFUSED 10.0.0.5:5432'))).toEqual({ status: 500, body: { error: 'Internal Server Error' } });
expect(toResponse(new HttpError(503, 'Redis is down at 10.0.0.7'))).toEqual({ status: 503, body: { error: 'Internal Server Error' } });
expect(toResponse('oops')).toEqual({ status: 500, body: { error: 'Internal Server Error' } }); expect(toResponse(null)).toEqual({ status: 500, body: { error: 'Internal Server Error' } });