Skip to content

Commit

Permalink
Merge pull request #453 from nervosnetwork/refactor-internal-exceptions
Browse files Browse the repository at this point in the history
refactor: refactor internal exceptions
  • Loading branch information
Keith-CY committed Jul 15, 2020
2 parents 92e5f25 + 54d9c8d commit c8a57ce
Show file tree
Hide file tree
Showing 38 changed files with 666 additions and 134 deletions.
16 changes: 8 additions & 8 deletions packages/ckb-sdk-core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference types="../types/global" />

import RPC from '@nervosnetwork/ckb-sdk-rpc'
import { ArgumentRequired } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import { ParameterRequiredException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import * as utils from '@nervosnetwork/ckb-sdk-utils'

import generateRawTransaction, { Cell, RawTransactionParamsBase } from './generateRawTransaction'
Expand Down Expand Up @@ -99,7 +99,7 @@ class CKB {
deps: Omit<DepCellInfo, 'outPoint'> | undefined = this.config.secp256k1Dep,
) => {
if (!deps) {
throw new ArgumentRequired('deps')
throw new ParameterRequiredException('deps')
}

return this.utils.scriptToHash({
Expand Down Expand Up @@ -199,7 +199,7 @@ class CKB {
transaction: CKBComponents.RawTransactionToSign,
cells: CachedCell[],
) => {
if (!key) throw new ArgumentRequired('Private key or address object')
if (!key) throw new ParameterRequiredException('Private key or address object')
this.#validateTransactionToSign(transaction)

const transactionHash = this.utils.rawTransactionToHash(transaction)
Expand Down Expand Up @@ -449,20 +449,20 @@ class CKB {

#secp256k1DepsShouldBeReady = () => {
if (!this.config.secp256k1Dep) {
throw new ArgumentRequired('Secp256k1 dep')
throw new ParameterRequiredException('Secp256k1 dep')
}
}

#DAODepsShouldBeReady = () => {
if (!this.config.daoDep) {
throw new ArgumentRequired('Dao dep')
throw new ParameterRequiredException('Dao dep')
}
}

#validateTransactionToSign = (transaction: CKBComponents.RawTransactionToSign) => {
if (!transaction) throw new ArgumentRequired('Transaction')
if (!transaction.witnesses) throw new ArgumentRequired('Witnesses')
if (!transaction.outputsData) throw new ArgumentRequired('OutputsData')
if (!transaction) throw new ParameterRequiredException('Transaction')
if (!transaction.witnesses) throw new ParameterRequiredException('Witnesses')
if (!transaction.outputsData) throw new ParameterRequiredException('OutputsData')
if (transaction.outputsData.length < transaction.outputs.length) throw new Error('Invalid count of outputsData')
}

Expand Down
6 changes: 3 additions & 3 deletions packages/ckb-sdk-core/src/loadCells.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import RPC from '@nervosnetwork/ckb-sdk-rpc'
import { assertToBeHexStringOrBigint } from '@nervosnetwork/ckb-sdk-utils/lib/validators'
import { JSBI } from '@nervosnetwork/ckb-sdk-utils'
import { ArgumentRequired } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import { ParameterRequiredException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'

const getMinBigInt = (x: JSBI, y: JSBI) => {
return JSBI.greaterThan(x, y) ? y : x
Expand All @@ -18,10 +18,10 @@ interface LoadCellsProps {
const loadCells = async ({ lockHash, start = '0x0', end, STEP = '0x64', rpc }: LoadCellsProps) => {
console.warn(`This method is only for demo, don't use it in production`)
if (!lockHash) {
throw new ArgumentRequired('lockHash')
throw new ParameterRequiredException('lockHash')
}
if (!rpc) {
throw new ArgumentRequired('RPC object')
throw new ParameterRequiredException('RPC object')
}
assertToBeHexStringOrBigint(start)

Expand Down
8 changes: 4 additions & 4 deletions packages/ckb-sdk-core/src/signWitnesses.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ArgumentRequired } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import { ParameterRequiredException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import signWitnessGroup from './signWitnessGroup'
import groupScripts from './groupScripts'

Expand Down Expand Up @@ -41,8 +41,8 @@ const signWitnesses: SignWitnesses = (key: SignatureProvider | Map<LockHash, Sig
inputCells: CachedLock[]
skipMissingKeys: boolean
}) => {
if (!key) throw new ArgumentRequired('Signature provider')
if (!transactionHash) throw new ArgumentRequired('Transaction hash')
if (!key) throw new ParameterRequiredException('Signature provider')
if (!transactionHash) throw new ParameterRequiredException('Transaction hash')
if (!witnesses.length) throw new Error('Witnesses is empty')

if (isMap(key)) {
Expand All @@ -60,7 +60,7 @@ const signWitnesses: SignWitnesses = (key: SignatureProvider | Map<LockHash, Sig
}
}

const ws = [...indices.map((idx) => witnesses[idx]), ...restWitnesses]
const ws = [...indices.map(idx => witnesses[idx]), ...restWitnesses]

const witnessIncludeSignature = signWitnessGroup(sk, transactionHash, ws)[0]
rawWitnesses[indices[0]] = witnessIncludeSignature
Expand Down
6 changes: 3 additions & 3 deletions packages/ckb-sdk-rpc/__tests__/ckb-rpc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1451,7 +1451,7 @@ describe('Test with mock', () => {

describe('ckb-rpc errors', () => {
it('throw raw error', async () => {
expect(() => rpc.getBlock(0)).toThrow('Hash 0 should be type of string')
expect(() => rpc.getBlock(0)).toThrow('Expect hash to be string, but 0 received')
})

describe('batch request', () => {
Expand All @@ -1465,7 +1465,7 @@ describe('Test with mock', () => {
const batch = rpc.createBatchRequest([['getBlock', [0]]])
batch
.exec()
.catch(err => expect(err).toEqual(new Error(`[Batch Request 0]: Hash 0 should be type of string`)))
.catch(err => expect(err).toEqual(new Error(`[Batch Request 0]: Expect hash to be string, but 0 received`)))
})

it('should return an error of mismatched json rpc id', async () => {
Expand All @@ -1491,7 +1491,7 @@ describe('Test with mock', () => {
],
})
const res = await batch.exec()
expect(res[0]).toEqual(new Error(`[Batch Request 0]: JSONRPC id not matched`))
expect(res[0]).toEqual(new Error(`[Batch Request 0]: Expect json rpc id to be 10000, but 10001 received`))
})
})
})
Expand Down
74 changes: 74 additions & 0 deletions packages/ckb-sdk-rpc/__tests__/exceptions/fixtures.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"IdNotMatchException": {
"params": [10000, 10001],
"expected": {
"code": 201,
"message": "Expect json rpc id to be 10000, but 10001 received"
}
},
"ResponseException": {
"params": ["Response_Err_Message"],
"expected": {
"code": 204,
"message": "Response_Err_Message"
}
},
"PageSizeTooLargeException": {
"params": [51, 50],
"expected": {
"code": 101,
"message": "Expect page size to be at most 50, but 51 received"
}
},
"PageSizeTooSmallException": {
"params": [-1, 0],
"expected": {
"code": 101,
"message": "Expect page size to be at least 0, but -1 received"
}
},
"OutputsValidatorTypeException": {
"params": [],
"expected": {
"code": 101,
"message": "Expect outputs validator to be 'default' or 'passthrough'"
}
},
"BigintOrHexStringTypeException": {
"params": ["ab"],
"expected": {
"code": 101,
"message": "Expect number to be bigint or hex string, but ab received"
}
},
"StringHashTypeException": {
"params": [1],
"expected": {
"code": 101,
"message": "Expect hash to be string, but 1 received"
}
},
"MethodInBatchNotFoundException": {
"params": ["Method_Name"],
"expected": {
"code": 202,
"message": "[Batch Request]: Method Method_Name is not found"
}
},
"PayloadInBatchException": {
"params": [1, "Payload_Err_Message"],
"expected": {
"code": 203,
"index": 1,
"message": "[Batch Request 1]: Payload_Err_Message"
}
},
"IdNotMatchedInBatchException": {
"params": [1, 10000, 10001],
"expected": {
"code": 201,
"index": 1,
"message": "[Batch Request 1]: Expect json rpc id to be 10000, but 10001 received"
}
}
}
18 changes: 18 additions & 0 deletions packages/ckb-sdk-rpc/__tests__/exceptions/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const exceptions = require('../../lib/exceptions')
const fixtures = require('./fixtures.json')

describe('Test exceptions', () => {
const fixtureTable = Object.entries(fixtures).map(([exceptionName, { params, expected }]) => [
exceptionName,
params,
expected,
])
test.each(fixtureTable)(`%s`, (exceptionName, params, expected) => {
const err = new exceptions[exceptionName](...params)
expect(err.code).toBe(expected.code)
expect(err.message).toBe(expected.message)
if (err.index) {
expect(err.index).toBe(expected.index)
}
})
})
12 changes: 6 additions & 6 deletions packages/ckb-sdk-rpc/__tests__/formatters/params.fixtures.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
},
{
"param": 20,
"exception": "The number 20 should be a bigint or a hex string"
"exception": "Expect number to be bigint or hex string, but 20 received"
},
{
"param": null,
"exception": "The number null should be a bigint or a hex string"
"exception": "Expect number to be bigint or hex string, but null received"
},
{
"param": "1",
Expand All @@ -28,7 +28,7 @@
},
{
"param": 1,
"exception": "Hash 1 should be type of string"
"exception": "Expect hash to be string, but 1 received"
}
],
"toOutPoint": [
Expand Down Expand Up @@ -345,15 +345,15 @@
},
{
"param": -1,
"exception": "Page size is expected to be non-negative"
"exception": "Expect page size to be at least 0, but -1 received"
},
{
"param": 50,
"expected": "0x32"
},
{
"param": 51,
"exception": "Page size is up to 50"
"exception": "Expect page size to be at most 50, but 51 received"
}
],
"toReverseOrder": [
Expand Down Expand Up @@ -388,7 +388,7 @@
},
{
"param": "unknown",
"exception": "Outputs validator should be default or passthrough"
"exception": "Expect outputs validator to be 'default' or 'passthrough'"
}
]
}
4 changes: 3 additions & 1 deletion packages/ckb-sdk-rpc/__tests__/method.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ describe('Test Method', () => {
result: null,
},
})
await method.call().catch(err => expect(err).toEqual(new Error(`JSONRPC id not matched`)))
await method
.call()
.catch(err => expect(err).toEqual(new Error(`Expect json rpc id to be 10000, but 10001 received`)))
})

it('returns with error', async () => {
Expand Down
8 changes: 8 additions & 0 deletions packages/ckb-sdk-rpc/src/exceptions/ErrorCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export enum ErrorCode {
IdNotMatch = 201,
MethodNotFound = 202,
PayloadMessage = 203,
ResponseMessage = 204,
}

export default ErrorCode
39 changes: 39 additions & 0 deletions packages/ckb-sdk-rpc/src/exceptions/batch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import ErrorCode from './ErrorCode'
import { IdNotMatchException } from './rpc'

const ERROR_LABEL = 'Batch Request'

export class MethodInBatchNotFoundException extends Error {
code = ErrorCode.MethodNotFound

constructor(name: string) {
super(`[${ERROR_LABEL}]: Method ${name} is not found`)
}
}

export class PayloadInBatchException extends Error {
code = ErrorCode.PayloadMessage

index: number | undefined

constructor(index: number, message: string) {
super(`[${ERROR_LABEL} ${index}]: ${message}`)
this.index = index
}
}

export class IdNotMatchedInBatchException extends IdNotMatchException {
index: number | undefined

constructor(index: number, requestId: number, responseId: number) {
super(requestId, responseId)
this.message = `[${ERROR_LABEL} ${index}]: ${this.message}`
this.index = index
}
}

export default {
MethodInBatchNotFoundException,
PayloadInBatchException,
IdNotMatchedInBatchException,
}
49 changes: 49 additions & 0 deletions packages/ckb-sdk-rpc/src/exceptions/formatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ErrorCode } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'

export class PageSizeTooLargeException extends RangeError {
code = ErrorCode.ParameterInvalid

constructor(pageSize: bigint | string, maxSize: number) {
super(`Expect page size to be at most ${maxSize}, but ${pageSize} received`)
}
}

export class PageSizeTooSmallException extends RangeError {
code = ErrorCode.ParameterInvalid

constructor(pageSize: bigint | string, minSize: number) {
super(`Expect page size to be at least ${minSize}, but ${pageSize} received`)
}
}

export class OutputsValidatorTypeException extends TypeError {
code = ErrorCode.ParameterInvalid

constructor() {
super(`Expect outputs validator to be 'default' or 'passthrough'`)
}
}

export class BigintOrHexStringTypeException extends TypeError {
code = ErrorCode.ParameterInvalid

constructor(value: any) {
super(`Expect number to be bigint or hex string, but ${value} received`)
}
}

export class StringHashTypeException extends TypeError {
code = ErrorCode.ParameterInvalid

constructor(hash: any) {
super(`Expect hash to be string, but ${hash} received`)
}
}

export default {
PageSizeTooLargeException,
PageSizeTooSmallException,
OutputsValidatorTypeException,
BigintOrHexStringTypeException,
StringHashTypeException,
}
4 changes: 4 additions & 0 deletions packages/ckb-sdk-rpc/src/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { HexStringWithout0xException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
export * from './formatter'
export * from './rpc'
export * from './batch'
Loading

0 comments on commit c8a57ce

Please sign in to comment.