Skip to content
Advertisement

Parsing error message using substr and indexOf not working

I’m trying to extract a substring from an error message I receive and parse it to JSON. However it seems something with the indexOf or the substring method is not working as expected.

Here’s the full error message I’m trying to parse:

processing response error (body="{"jsonrpc":"2.0","id":223,"error":{"code":-32000,"message":"intrinsic gas too low"}}", error={"code":-32000}, requestBody="{"method":"eth_sendRawTransaction","params":["0xf8a85b843b9aca0082520894ad6d458402f60fd3bd25163575031acdce07538d80b844a9059cbb000000000000000000000000ca3f2ee61e5afd8072e351fff1e6da3d47e0e9ab0000000000000000000000000000000000000000000000000de0b6b3a764000029a0c9bc6207b2c1bd1413235f28200fef961acc00aa1e9c38fdb0c864a64441b5afa0169756bd13450d07c1bfbcbc12902d77015b832a1aab4d9a3f25b40d0259fa07"],"id":223,"jsonrpc":"2.0"}", requestMethod="POST")

Basically I’m trying to extract this JSON string programatically:

"{"jsonrpc":"2.0","id":223,"error":{"code":-32000,"message":"intrinsic gas too low"}}"

To do this I wanted to use a combination of indexOf and the substring method:

.catch(e => {
        const firstChar = e.message.indexOf('{')
        const lastChar = e.message.indexOf('}') + 1
        console.log(firstChar, lastChar)
        const substring = e.message.substr(firstChar, lastChar)
        console.log(substring)
      })

Somehow it seems the find the correct start index but it misses the correct end and I have no idea why. Here’s the result:

{"jsonrpc":"2.0","id":57,"error":{"code":-32000,"message":"intrinsic gas too low"}}", error={"code":-32000}, reque

If anyone has an idea what I’m doing wrong here and how to fix it, please let me know!

Advertisement

Answer

The javascript substr function takes 2 params.

First being the start index and second being the length of the string from the start index that you want to take.

Check the snippet.

const message = `processing response error (body="{"jsonrpc":"2.0","id":223,"error":{"code":-32000,"message":"intrinsic gas too low"}}", error={"code":-32000}, requestBody="{"method":"eth_sendRawTransaction","params":["0xf8a85b843b9aca0082520894ad6d458402f60fd3bd25163575031acdce07538d80b844a9059cbb000000000000000000000000ca3f2ee61e5afd8072e351fff1e6da3d47e0e9ab0000000000000000000000000000000000000000000000000de0b6b3a764000029a0c9bc6207b2c1bd1413235f28200fef961acc00aa1e9c38fdb0c864a64441b5afa0169756bd13450d07c1bfbcbc12902d77015b832a1aab4d9a3f25b40d0259fa07"],"id":223,"jsonrpc":"2.0"}", requestMethod="POST")`;

const firstChar = message.indexOf('{')
const lastChar = message.indexOf('}') + 1
console.log(firstChar, lastChar)
const substring = message.substr(firstChar, lastChar - firstChar + 1)
console.log(substring)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement