diff --git a/include/spdk/jsonrpc.h b/include/spdk/jsonrpc.h index 0ca85ea5f..7a7d21657 100644 --- a/include/spdk/jsonrpc.h +++ b/include/spdk/jsonrpc.h @@ -107,6 +107,20 @@ void spdk_jsonrpc_end_result(struct spdk_jsonrpc_request *request, struct spdk_j void spdk_jsonrpc_send_error_response(struct spdk_jsonrpc_request *request, int error_code, const char *msg); +/** + * Send an error response to a JSON-RPC request. + * + * \param request JSON-RPC request to respond to. + * \param error_code Integer error code to return (may be one of the SPDK_JSONRPC_ERROR_ errors, + * or a custom error code). + * \param fmt Printf-like format string. + * + * This is shorthand for printf() + spdk_jsonrpc_send_error_response(). + */ +void spdk_jsonrpc_send_error_response_fmt(struct spdk_jsonrpc_request *request, + int error_code, const char *fmt, ...) __attribute__((format(printf, 3, 4))); + + #ifdef __cplusplus } #endif diff --git a/lib/jsonrpc/jsonrpc_server.c b/lib/jsonrpc/jsonrpc_server.c index d7f564000..0d799d341 100644 --- a/lib/jsonrpc/jsonrpc_server.c +++ b/lib/jsonrpc/jsonrpc_server.c @@ -318,4 +318,35 @@ spdk_jsonrpc_send_error_response(struct spdk_jsonrpc_request *request, end_response(request, w); } +void +spdk_jsonrpc_send_error_response_fmt(struct spdk_jsonrpc_request *request, + int error_code, const char *fmt, ...) +{ + struct spdk_json_write_ctx *w; + va_list args; + + if (request->id.type == SPDK_JSON_VAL_INVALID) { + /* For error responses, if id is missing, explicitly respond with "id": null. */ + request->id.type = SPDK_JSON_VAL_NULL; + } + + w = begin_response(request); + if (w == NULL) { + free(request); + return; + } + + spdk_json_write_name(w, "error"); + spdk_json_write_object_begin(w); + spdk_json_write_name(w, "code"); + spdk_json_write_int32(w, error_code); + spdk_json_write_name(w, "message"); + va_start(args, fmt); + spdk_json_write_string_fmt_v(w, fmt, args); + va_end(args); + spdk_json_write_object_end(w); + + end_response(request, w); +} + SPDK_LOG_REGISTER_COMPONENT("rpc", SPDK_LOG_RPC)