From 2307dbec579ceaf60aa3afd5f338ecfba127f104 Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Wed, 6 Oct 2021 10:50:08 +0200 Subject: [PATCH] Add support for producing custom error codes from request hanlers --- json_rpc/errors.nim | 5 +++++ json_rpc/router.nim | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/json_rpc/errors.nim b/json_rpc/errors.nim index c48bc3a..b277a30 100644 --- a/json_rpc/errors.nim +++ b/json_rpc/errors.nim @@ -10,3 +10,8 @@ type RpcBindError* = object of JsonRpcError RpcAddressUnresolvableError* = object of JsonRpcError + + InvalidRequest* = object of JsonRpcError + ## This could be raised by request handlers when the server + ## needs to respond with a custom error code. + code*: int diff --git a/json_rpc/router.nim b/json_rpc/router.nim index 45174ec..c70e77b 100644 --- a/json_rpc/router.nim +++ b/json_rpc/router.nim @@ -1,7 +1,7 @@ import std/[macros, options, strutils, tables], chronicles, chronos, json_serialization/writer, - ./jsonmarshal + ./jsonmarshal, ./errors export chronos, jsonmarshal @@ -36,7 +36,7 @@ proc newRpcRouter*: RpcRouter {.deprecated.} = proc register*(router: var RpcRouter, path: string, call: RpcProc) = router.procs.add(path, call) -proc clear*(router: var RpcRouter) = +proc clear*(router: var RpcRouter) = router.procs.clear proc hasMethod*(router: RpcRouter, methodName: string): bool = router.procs.hasKey(methodName) @@ -80,7 +80,8 @@ proc route*(router: RpcRouter, node: JsonNode): Future[StringOfJson] {.async, gc try: let res = await rpcProc(if params == nil: newJArray() else: params) return wrapReply(id, res) - + except InvalidRequest as err: + return wrapError(err.code, err.msg) except CatchableError as err: debug "Error occurred within RPC", methodName = methodName, err = err.msg return wrapError(