我需要发送 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
一次。