Search code examples
dvibed

How to send error response with JSON body


I need to send JSON response with, for example, 403 HTTP error code. How can I achieve this in vibe.d?

I currently use this code:

T enforceCode(T)(HTTPServerResponse res, T value, ErrorCodes code,
    HTTPStatus status = HTTPStatus.forbidden)
{
    if (!value) {
        res.writeJsonBody(["code": code], status);

        enforceHTTP(false, status);
    }
    return value;
}

void sendCode(T)(HTTPServerResponse res, ErrorCodes code, T errorInfo,
    HTTPStatus status = HTTPStatus.forbidden)
{
    import vibe.data.json;

    res.writeJsonBody([
        "code": Json(cast(int)code),
        "info": Json(serializeToJsonString(errorInfo))
    ], status);

    enforceHTTP(false, status); // I need to terminate current action
}

But other developers complain that error event triggered twice in the client application. With commented out writeJsonBody only once.


Solution

  • It was bug at client-side and not in above code.