|
| 1 | +import { describe, it, expect } from 'vitest'; |
| 2 | +import { RequestError } from './request-error'; |
| 3 | + |
| 4 | +describe('RequestError', () => { |
| 5 | + it('extracts message, code and details from a structured JSON body', () => { |
| 6 | + const body = JSON.stringify({ |
| 7 | + message: 'Components limit reached (10/10).', |
| 8 | + code: 'LIMIT_EXCEEDED', |
| 9 | + details: { limitType: 'componentsPerAccount', current: 10, max: 10 }, |
| 10 | + }); |
| 11 | + const err = new RequestError(403, 'Forbidden', body); |
| 12 | + expect(err.status).toBe(403); |
| 13 | + expect(err.code).toBe('LIMIT_EXCEEDED'); |
| 14 | + expect(err.details).toEqual({ |
| 15 | + limitType: 'componentsPerAccount', |
| 16 | + current: 10, |
| 17 | + max: 10, |
| 18 | + }); |
| 19 | + expect(err.message).toBe('Components limit reached (10/10).'); |
| 20 | + expect(err.body).toBe(body); |
| 21 | + }); |
| 22 | + |
| 23 | + it('leaves code and details undefined when the body has only a message', () => { |
| 24 | + const err = new RequestError(404, 'Not Found', JSON.stringify({ |
| 25 | + message: 'Item not found', |
| 26 | + })); |
| 27 | + expect(err.message).toBe('Item not found'); |
| 28 | + expect(err.code).toBeUndefined(); |
| 29 | + expect(err.details).toBeUndefined(); |
| 30 | + }); |
| 31 | + |
| 32 | + it('falls back to a status line when the body is not JSON', () => { |
| 33 | + const err = new RequestError(502, 'Bad Gateway', '<html>error</html>'); |
| 34 | + expect(err.message).toBe('Bad Gateway (502)'); |
| 35 | + expect(err.code).toBeUndefined(); |
| 36 | + expect(err.details).toBeUndefined(); |
| 37 | + expect(err.body).toBe('<html>error</html>'); |
| 38 | + }); |
| 39 | + |
| 40 | + it('falls back to a status line for an empty body', () => { |
| 41 | + const err = new RequestError(500, 'Internal Server Error', ''); |
| 42 | + expect(err.message).toBe('Internal Server Error (500)'); |
| 43 | + }); |
| 44 | + |
| 45 | + it('falls back when the JSON body is not an object', () => { |
| 46 | + const err = new RequestError(400, 'Bad Request', '"just a string"'); |
| 47 | + expect(err.message).toBe('Bad Request (400)'); |
| 48 | + expect(err.code).toBeUndefined(); |
| 49 | + }); |
| 50 | + |
| 51 | + it('ignores non-string message and code fields', () => { |
| 52 | + const err = new RequestError(400, 'Bad Request', JSON.stringify({ |
| 53 | + message: 123, |
| 54 | + code: { nested: true }, |
| 55 | + })); |
| 56 | + expect(err.message).toBe('Bad Request (400)'); |
| 57 | + expect(err.code).toBeUndefined(); |
| 58 | + }); |
| 59 | + |
| 60 | + it('is an instance of Error and RequestError with the right name', () => { |
| 61 | + const err = new RequestError(403, 'Forbidden', ''); |
| 62 | + expect(err).toBeInstanceOf(Error); |
| 63 | + expect(err).toBeInstanceOf(RequestError); |
| 64 | + expect(err.name).toBe('RequestError'); |
| 65 | + }); |
| 66 | +}); |
0 commit comments