[Ethereum] How to get the revert reason of a call in Solidity so that I can use it in the same on-chain transaction

contract-designcontract-developmentrevert-opcodesoliditytransactions

I want to get the revert reason of a failed call and then use that revert reason in the same on-chain transaction. Is this possible?

Best Answer

I modified shanes answer:

function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
    // If the _res length is less than 68, then the transaction failed silently (without a revert message)
    if (_returnData.length < 68) return 'Transaction reverted silently';

    assembly {
        // Slice the sighash.
        _returnData := add(_returnData, 0x04)
    }
    return abi.decode(_returnData, (string)); // All that remains is the revert string
}

It seems to work and that way we dont need the extra library