如何使用 JSON 正文发送错误响应
How to send error response with JSON body
我需要发送 JSON 响应,例如 403 HTTP 错误代码。我怎样才能在 vibe.d 中做到这一点?
我目前使用这个代码:
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
}
但其他开发人员抱怨错误事件在客户端应用程序中触发了两次。仅注释掉 writeJsonBody
一次。
这是客户端的错误,而不是上面的代码。
我需要发送 JSON 响应,例如 403 HTTP 错误代码。我怎样才能在 vibe.d 中做到这一点?
我目前使用这个代码:
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
}
但其他开发人员抱怨错误事件在客户端应用程序中触发了两次。仅注释掉 writeJsonBody
一次。
这是客户端的错误,而不是上面的代码。