The following code examples show how to create different error actions.

An error action can include a delay to simulate a service that hangs before dropping the connection, which is useful for testing timeout handling.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .error(
        error()
            .withDropConnection(true)
            .withDelay(TimeUnit.SECONDS, 5)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "delay": {
            "timeUnit": "SECONDS",
            "value": 5
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpError, HttpRequest, Delay

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).error(
    HttpError(drop_connection=True, delay=Delay(time_unit="SECONDS", value=5))
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).error(
    MockServer::HttpError.new(
        drop_connection: true,
        delay: MockServer::Delay.new(time_unit: 'SECONDS', value: 5)
    )
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().Path("/some/path"),
).RespondWithError(
    mockserver.Error().DropConnection(true).WithDelay("SECONDS", 5),
)
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpError"": {
        ""dropConnection"": true,
        ""delay"": {
            ""timeUnit"": ""SECONDS"",
            ""value"": 5
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "delay": {
            "timeUnit": "SECONDS",
            "value": 5
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "delay": {
            "timeUnit": "SECONDS",
            "value": 5
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "delay": {
            "timeUnit": "SECONDS",
            "value": 5
        }
    }
}'

See REST API for full JSON specification

// generate random bytes
byte[] randomByteArray = new byte[25];
new Random().nextBytes(randomByteArray);

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .error(
        error()
            .withDropConnection(true)
            .withResponseBytes(randomByteArray)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "responseBytes": "eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg=="
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpError, HttpRequest

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).error(
    HttpError(drop_connection=True, response_bytes="eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg==")
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).error(
    MockServer::HttpError.new(
        drop_connection: true,
        response_bytes: 'eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg=='
    )
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().Path("/some/path"),
).RespondWithError(
    mockserver.Error().DropConnection(true).ResponseBytes("eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg=="),
)
using MockServer.Client;
using MockServer.Client.Models;

using var client = new MockServerClient("localhost", 1080);
client.When(
    HttpRequest.Request().WithPath("/some/path")
).Error(
    HttpError.Error()
        .WithDropConnection(true)
        .WithResponseBytes("eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg==")
);
use mockserver_client::{ClientBuilder, HttpRequest, HttpError};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(HttpRequest::new().path("/some/path"))
    .error(
        HttpError::new()
            .drop_connection(true)
            .response_bytes("eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg==")
    )
    .unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
use MockServer\HttpError;

$client = new MockServerClient('localhost', 1080);
$client->when(
    HttpRequest::request()
        ->path('/some/path')
)->error(
    HttpError::error()
        ->dropConnection(true)
        ->responseBytes('eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg==')
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "dropConnection": true,
        "responseBytes": "eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg=="
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .error(
        error()
            .withDropConnection(true)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpError" : {
        "dropConnection" : true
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpError, HttpRequest

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).error(
    HttpError(drop_connection=True)
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).error(
    MockServer::HttpError.new(drop_connection: true)
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().Path("/some/path"),
).RespondWithError(
    mockserver.Error().DropConnection(true),
)
using MockServer.Client;
using MockServer.Client.Models;

using var client = new MockServerClient("localhost", 1080);
client.When(
    HttpRequest.Request().WithPath("/some/path")
).Error(
    HttpError.Error().WithDropConnection(true)
);
use mockserver_client::{ClientBuilder, HttpRequest, HttpError};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(HttpRequest::new().path("/some/path"))
    .error(HttpError::new().drop_connection(true))
    .unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
use MockServer\HttpError;

$client = new MockServerClient('localhost', 1080);
$client->when(
    HttpRequest::request()
        ->path('/some/path')
)->error(
    HttpError::error()
        ->dropConnection(true)
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpError" : {
        "dropConnection" : true
    }
}'

See REST API for full JSON specification

Use respondBeforeBody on the request matcher to dispatch the configured response before MockServer reads the request body. The matcher must not include a body matcher and only RESPONSE and ERROR actions are supported. The connection is always closed after the response (the inbound body has not been consumed, so reuse is unsafe), so any closeSocket value is ignored — set keepAliveOverride(false) on the response if you want the Connection: close header on the wire. HTTP/1.1 only — HTTP/2 connections fall through to the standard pipeline. This is useful for reproducing client behaviour when a server responds and closes mid-upload.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("POST")
            .withPath("/upload")
            .withRespondBeforeBody(true)
    )
    .respond(
        response()
            .withStatusCode(403)
            .withBody("forbidden")
            .withConnectionOptions(
                connectionOptions().withKeepAliveOverride(false)
            )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "method": "POST",
        "path": "/upload",
        "respondBeforeBody": true
    },
    "httpResponse": {
        "statusCode": 403,
        "body": "forbidden",
        "connectionOptions": {
            "keepAliveOverride": false
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "method": "POST",
        "path": "/upload",
        "respondBeforeBody": True
    },
    "httpResponse": {
        "statusCode": 403,
        "body": "forbidden",
        "connectionOptions": {
            "keepAliveOverride": False
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "method": "POST",
        "path": "/upload",
        "respondBeforeBody": true
    },
    "httpResponse": {
        "statusCode": 403,
        "body": "forbidden",
        "connectionOptions": {
            "keepAliveOverride": false
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "method": "POST",
        "path": "/upload",
        "respondBeforeBody": true
    },
    "httpResponse": {
        "statusCode": 403,
        "body": "forbidden",
        "connectionOptions": {
            "keepAliveOverride": false
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""method"": ""POST"",
        ""path"": ""/upload"",
        ""respondBeforeBody"": true
    },
    ""httpResponse"": {
        ""statusCode"": 403,
        ""body"": ""forbidden"",
        ""connectionOptions"": {
            ""keepAliveOverride"": false
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "method": "POST",
        "path": "/upload",
        "respondBeforeBody": true
    },
    "httpResponse": {
        "statusCode": 403,
        "body": "forbidden",
        "connectionOptions": {
            "keepAliveOverride": false
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest" : {
        "method" : "POST",
        "path" : "/upload",
        "respondBeforeBody" : true
    },
    "httpResponse" : {
        "statusCode" : 403,
        "body" : "forbidden",
        "connectionOptions" : {
            "keepAliveOverride" : false
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "method" : "POST",
        "path" : "/upload",
        "respondBeforeBody" : true
    },
    "httpResponse" : {
        "statusCode" : 403,
        "body" : "forbidden",
        "connectionOptions" : {
            "keepAliveOverride" : false
        }
    }
}'

See REST API for full JSON specification

For resilience testing of clients that must cope with mid-stream resets, an error action can reset just the matched request stream instead of returning a response. Set streamError to the stream error code to send: over HTTP/2 MockServer sends an RST_STREAM for that stream (RFC 7540 codes, e.g. REFUSED_STREAM = 7), and over HTTP/3 a QUIC RESET_STREAM (RFC 9114 codes, e.g. H3_REQUEST_CANCELLED = 268 / 0x10c). Other streams multiplexed on the same connection are unaffected.

HTTP/1.1 caveat: HTTP/1.1 has no stream concept, so a request that matches over HTTP/1.1 cannot be reset at the stream level — MockServer instead drops the whole connection (the same behaviour as dropConnection).

Precedence: if both streamError and dropConnection are set on the same error action, streamError wins and dropConnection is ignored (over HTTP/1.1 the stream-error fallback drops the connection anyway).

Common stream error codes:

ProtocolNameCode
HTTP/2NO_ERROR0
HTTP/2PROTOCOL_ERROR1
HTTP/2INTERNAL_ERROR2
HTTP/2REFUSED_STREAM7
HTTP/2CANCEL8
HTTP/2ENHANCE_YOUR_CALM11
HTTP/2HTTP_1_1_REQUIRED13
HTTP/3H3_REQUEST_REJECTED267 (0x10b)
HTTP/3H3_REQUEST_CANCELLED268 (0x10c)
HTTP/3H3_INTERNAL_ERROR258 (0x102)
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .error(
        error()
            .withStreamError(HttpError.StreamErrorCode.REFUSED_STREAM)
    );

The raw numeric form error().withStreamError(7L) and the error().withStreamErrorCodeName("REFUSED_STREAM") convenience are equivalent.

var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "streamError": 7
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpError, HttpRequest

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).error(
    HttpError(stream_error=7)
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).error(
    MockServer::HttpError.new(stream_error: 7)
)
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "streamError": 7
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpError"": {
        ""streamError"": 7
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "streamError": 7
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpError": {
        "streamError": 7
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpError" : {
        "streamError" : 7
    }
}'

See REST API for full JSON specification