Fix error message on content-type mismatch (#2140)
This commit is contained in:
parent
dc196be807
commit
9dbd9d87d4
25
lib/url.js
25
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 })
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user