Add support for producing custom error codes from request hanlers

This commit is contained in:
Zahary Karadjov 2021-10-06 10:50:08 +02:00
parent b2417fc071
commit 2307dbec57
2 changed files with 9 additions and 3 deletions

View File

@ -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

View File

@ -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(