Mock Error Responses in MSW

Share this video with your friends

Send Tweet

Error handling is crucial for a great user experience. Learn how to reproduce any error response with Mock Service Worker, be it a 404, 500, or any other HTTP error response.

~ a year ago

I ran into an issue with return HttpResponse(null, { status: 500 }). Is this still the API because the documentation for HttpResponse seems to imply that you cannot send null: https://mswjs.io/docs/api/http-response#call-signature.

Also, there seems to be a static method HttpResponse.error but it says in the documentation that "neither HttpResponse.error() nor Response.error() allow customizing the network error response".

With that said, the error I see displayed in the UI is "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data". This doesn't seem as useful as the error message presented in this video.

Artem Zakharchenkoinstructor
~ a year ago

Hi! Thanks for letting me know.

The docs mention that the HttpResponse construct signature is equal to the Response construct signature, whose body argument supports both null and undefined. The docs repeat that in types a bit incorrectly, it seems, confusing you whether null is allowed. It is.

The HttpResponse.error() static method is the proxy for the standard Response.error() method, and is meant for network errors, not error responses. I mention the difference between the two on this page.

Regarding the SyntaxError you experienced, it sounds like something else is off. If you share a repository/sandbox, I can take a look and help you figure out why you're getting the JSON.parse error instead.