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 {
|
export class ResponseAssertError extends Error {
|
||||||
constructor (res, { method } = {}) {
|
constructor (res, { message, method } = {}) {
|
||||||
if (method) {
|
const urlPart = method ? `${method} ${res.url}` : res.url
|
||||||
super(`${method} ${res.url}: ${res.status} ${res.statusText}`)
|
const msgPart = message ?? `${res.status} ${res.statusText}`
|
||||||
} else {
|
super(`${urlPart}: ${msgPart}`)
|
||||||
super(`${res.url}: ${res.status} ${res.statusText}`)
|
|
||||||
}
|
|
||||||
this.name = 'ResponseAssertError'
|
this.name = 'ResponseAssertError'
|
||||||
// consume response body to avoid memory leaks
|
// consume response body to avoid memory leaks
|
||||||
// see https://github.com/nodejs/node/issues/51162
|
// 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 } = {}) {
|
export function assertResponseOk (res, { method } = {}) {
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new ResponseAssertError(res, { method })
|
throw new ResponseAssertError(res, { method })
|
||||||
@ -234,9 +240,12 @@ export function assertResponseOk (res, { method } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function assertContentTypeJson (res, { method } = {}) {
|
export function assertContentTypeJson (res, { method } = {}) {
|
||||||
|
const expected = 'application/json'
|
||||||
const contentType = res.headers.get('content-type')
|
const contentType = res.headers.get('content-type')
|
||||||
if (!contentType || !contentType.includes('application/json')) {
|
if (!contentType || !contentType.includes(expected)) {
|
||||||
throw new ResponseAssertError(res, { method })
|
// 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