← Усі задачіNode.js · Junior
HttpError і безпечна відповідь
Напишіть клас HttpError (наслідує Error, має status і message) і функцію toResponse(error) для обробника помилок сервера. Вона повертає { status, body: { error } }.
Для помилок клієнта (HttpError зі статусом 4xx) повідомлення показується як є. Усе інше - HttpError 5xx, звичайні Error, навіть кинуті рядки чи null - віддає { error: "Internal Server Error" }: статус 5xx зберігається, а для будь-чого, крім HttpError, він 500. Внутрішні деталі на кшталт адрес баз даних клієнт бачити не повинен.
Ctrl+Enter - запустити тести. Tab - відступ; щоб вийти з редактора клавіатурою, натисніть Esc, а потім Tab. Код зберігається в цьому браузері.
Тести (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' } });