From 9dbd9d87d43c38967e9955c0c56a8159c18c145a Mon Sep 17 00:00:00 2001 From: ekzyis Date: Mon, 28 Apr 2025 15:17:44 -0500 Subject: [PATCH] Fix error message on content-type mismatch (#2140) --- lib/url.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/lib/url.js b/lib/url.js index 3d636cd9..c6871fc8 100644 --- a/lib/url.js +++ b/lib/url.js @@ -214,12 +214,10 @@ export function parseNwcUrl (walletConnectUrl) { } export class ResponseAssertError extends Error { - constructor (res, { method } = {}) { - if (method) { - super(`${method} ${res.url}: ${res.status} ${res.statusText}`) - } else { - super(`${res.url}: ${res.status} ${res.statusText}`) - } + constructor (res, { message, method } = {}) { + const urlPart = method ? `${method} ${res.url}` : res.url + const msgPart = message ?? `${res.status} ${res.statusText}` + super(`${urlPart}: ${msgPart}`) this.name = 'ResponseAssertError' // consume response body to avoid memory leaks // see https://github.com/nodejs/node/issues/51162 @@ -227,6 +225,14 @@ export class ResponseAssertError extends Error { } } +class ContentTypeAssertError extends ResponseAssertError { + constructor (res, { method, expected, actual } = {}) { + const message = `wrong content-type: expected: ${expected}, got: ${actual}` + super(res, { method, message }) + this.name = 'ContentTypeAssertError' + } +} + export function assertResponseOk (res, { method } = {}) { if (!res.ok) { throw new ResponseAssertError(res, { method }) @@ -234,9 +240,12 @@ export function assertResponseOk (res, { method } = {}) { } export function assertContentTypeJson (res, { method } = {}) { + const expected = 'application/json' const contentType = res.headers.get('content-type') - if (!contentType || !contentType.includes('application/json')) { - throw new ResponseAssertError(res, { method }) + if (!contentType || !contentType.includes(expected)) { + // get first part of content-type without parameters like charset=utf-8 for less verbose error message + const actual = contentType.split(';')[0] + throw new ContentTypeAssertError(res, { method, expected, actual }) } }