mswMock Service Worker
  1. Recipes
  2. Mocking error responses

Mocking error responses

When it comes to mocking an error response, it's recommended to compose a valid response using res() composition chain, rather than throwing an exception inside a request handler. This is mainly to distinguish between internal and intended exceptions.

Exception originating from a request handler is gracefully handled as a 500 response from the Service Worker, but it's highly recommended to resolve it, as it indicates an error in your code.

By treating an error response as an actual response, and not an exception, you respect the standard and ensure your client code receives and handles a valid error response.

Examples

Here's an example on how to mock an error response for the login POST request:

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.post('/login', (req, res, ctx) => {
5 const { username } = req.body
6
7 return res(
8 // Send a valid HTTP status code
9 ctx.status(403),
10 // And a response body, if necessary
11 ctx.json({
12 errorMessage: `User '${username}' not found`,
13 }),
14 )
15 }),
16)
17
18worker.start()

Request

POST/login
Body
1{
2 "username": "admin"
3}

Response

403Forbidden
Body
1{
2 "errorMessage": "User 'admin' not found"
3}