Skip to content

Don't throw on 204 No Content when parsing response #193

@psixdev

Description

@psixdev

Hello, I ran into a little problem. Not sure if this is a bug in the library or the expected behavior.
I have a little wrapper over the library:

const api = ky.create({
	prefixUrl: '...' // server api url
});

function request({path, ...params}) {
	return api(path, params)
		.json()
		.catch((err) => {
			if (err.response) {
				return err.response.json().then((err) => {
					throw err;
				});
			} else {
				throw err;
			}
		});
}

It works great for get, post and patch requests, since they return json. However, it broke for delete request, which returned 204 No Content, with error SyntaxError: Unexpected end of JSON input.
Should the ky handle such situations and return null, for example? Or should I take care of this problem myself?
My current working solution:

function request({path, ...params}) {
	return api(path, params)
		.text()
		.then((text) => text && JSON.parse(text))
		.catch((err) => {
			if (err.response) {
				return err.response.json().then((err) => {
					throw err;
				});
			} else {
				throw err;
			}
		});
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions