question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Not responding with correct status code

See original GitHub issue

Environment

Name Version
msw 0.26.2
node 14.15.4
OS Windows 10

Request handlers

import { setupServer } from 'msw/node'
import { rest } from 'msw'

const handlers = [
  rest.patch("/api/Resources/:id", (req, res, ctx) => {
    if (!req.headers.has("Authorization")) {
      return res(ctx.status(401));
    }

    let element = serverData.findIndex((e) => e.id === req.params.id);

    if (element === -1) {
      // this code block is entered
      return res(ctx.status(404), ctx.text(""));
    } else {
      return res(ctx.status(204), ctx.text(""));
    }
  }),
  rest.get("/api/Resources", (req, res, ctx) => {
    if (!req.headers.has("Authorization")) {
      return res(ctx.status(401));
    }

    return res(
      ctx.status(200),
      ctx.json({
        "@odata/stuff": "string",
        values: serverData,
      })
    );
  }),
];

const server = setupServer(...handlers);

Actual request

fetch(`${baseUrl}/${data.id}`, {
      method: "PATCH",
      headers: authHeaderWithContentType,
      body: JSON.stringify(data),
    }).then(handleResponse);

const handleResponse = (response: Response): Promise<any> => {
  console.log(response.status);
  if (response.ok) {
    if (isJson(response)) {
      return response.json();
    } else {
      return response.text();
    }
  } else {
    console.log(response.statusText);
    const error = new ResponseError(response.statusText);
    error.response = response;
    throw error;
  }
};

Current behavior

It returns 200 as a status code. This changes when I change the status code of the second route. The code block that is supposed to return a 404 status is entered but doesn’t return as it seems. Am I missing something?

Expected behavior

It should return a 404 status code causing the fetch request to throw an error.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
flexwiecommented, Feb 26, 2021

I recreated the error in this repository:

https://github.com/flexwie/msw_error

Running npm test will result in a failed test run. I have uncommented another test, that is using the samen handler succesfully for better readability.

1reaction
flexwiecommented, Feb 19, 2021

Hey @kettanaito, we added that handleResponse function to throw an error if the status code is >2xx.

element does exists and is -1 (aka not found in the array), what is what I am describing with my test case:

it("should throw error on unknown id", async () => {
    const { update } = useResourceService(mockState as any);

    const response = async () =>
      await update({
        id: "123-456-78",
        no: "123",
        name: "New Name",
      });

    expect(response).toThrowError();
  });

When I try to return some text along the 404 status, the fetch call receives an undefined body and still a 200 status code.

I will try reproduce this issue in a repository and come back to you! Thanks for you assistance so far!

Read more comments on GitHub >

github_iconTop Results From Across the Web

HTTP response status codes - MDN Web Docs - Mozilla
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:
Read more >
List of HTTP status codes - Wikipedia
This is a list of Hypertext Transfer Protocol (HTTP) response status codes. Status codes are issued by a server in response to a...
Read more >
A Complete Guide and List of HTTP Status Codes
A complete list of HTTP status codes with explaination of what they are, why they occur and what you can do to fix...
Read more >
HTTP/1.1: Status Code Definitions
This interim response is used to inform the client that the initial part of the request has been received and has not yet...
Read more >
HTTP Status Codes - REST API Tutorial
The 102 (Processing) status code is an interim response used to inform the client that the server has accepted the complete request, but...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found