Macaulay2 » Documentation
Packages » JSONRPC » JSONRPCServer » handleRequest » JSONRPCError
next | previous | forward | backward | up | index | toc

# JSONRPCError -- class for JSON-RPC errors

- Usage:
    `JSONRPCError(errCode, msg, data)`
    `JSONRPCError(errCode, msg)`
- Inputs:
  - errCode, an integer,
  - msg, a string,
  - data, a thing,

## Description

This class is used to represent errors that occur during the processing of JSON-RPC requests. It provides a structured way to format error responses, including an error code, message, and optional additional data. This class ensures that errors are properly formatted according to the JSON-RPC 2.0 specification and can be easily included in responses to clients.

Consider the following example. The default response doesn't include a very useful error message.

    i1 : server = new JSONRPCServer

    o1 = server

    o1 : JSONRPCServer

    i2 : registerMethod(server, "divide", (x, y) -> x/y)

    i3 : handleRequest(server, makeRequest("divide", {1, 0}, 1))

    o3 = {"error": {"code": -32602, "message": "Invalid params"}, "jsonrpc":
         "2.0", "id": 1}

Let's replace it with a more useful one.

    i4 : registerMethod(server, "divide", (x, y) -> (
                 if zero y then JSONRPCError(-32001, "division by zero")
                 else x/y))

    i5 : handleRequest(server, makeRequest("divide", {1, 0}, 1))

    o5 = {"error": {"code": -32001, "message": "division by zero"}, "jsonrpc":
         "2.0", "id": 1}

    i6 : handleRequest(server, makeRequest("divide", {22, 7}, 1))

    o6 = {"result": 3.142857142857143, "jsonrpc": "2.0", "id": 1}

Note that the error codes -32000 to -32099 are reserved for use by JSON-RPC servers, so `errCode` should lie in this interval (although this isn't checked).

## Methods that use a JSON-RPC error:

- `NewFromMethod(JSONRPCError,ZZ,String)`
- `NewFromMethod(JSONRPCError,ZZ,String,Thing)`

## For the programmer

The object JSONRPCError is a self initializing type, with ancestor classes HashTable < Thing.

The source of this document is in /build/macaulay2-88fgJW/macaulay2-1.25.11+ds/M2/Macaulay2/packages/JSONRPC.m2:406:0.