Skip to content

Commit

Permalink
fix(cli):optimize error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ni00 authored and ysfscream committed Jun 28, 2023
1 parent 08229bb commit 585203b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
1 change: 0 additions & 1 deletion cli/src/lib/pub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const send = (
basicLog.connected()
const { topic, message, protobufPath, protobufMessageName, protobufFormat } = pubOpts
basicLog.publishing()

let bufferMessage = serializeProtobufToBuffer(message, protobufPath, protobufMessageName, protobufFormat)
client.publish(topic, bufferMessage, pubOpts.opts, (err) => {
if (err) {
Expand Down
23 changes: 14 additions & 9 deletions cli/src/utils/protobuf.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import protobuf from 'protobufjs'
import signale from './signale'

const convertObject = (raw: string | Buffer, format?: FormatType | undefined) => {
switch (format) {
Expand All @@ -25,13 +26,13 @@ export const serializeProtobufToBuffer = (
const rawData = convertObject(raw, format)
const err = Message.verify(rawData)
if (err) {
throw Error(err)
signale.warn(err)
}
const data = Message.create(rawData)
const serializedMessage = Message.encode(data).finish()
bufferMessage = Buffer.from(serializedMessage)
} catch (err) {
console.log(err)
} catch (err: unknown) {
signale.warn((err as Error).message.split('\n')[0])
}
}
return bufferMessage
Expand All @@ -44,12 +45,16 @@ export const deserializeBufferToProtobuf = (
to?: FormatType,
): any => {
if (protobufPath && protobufMessageName) {
const root = protobuf.loadSync(protobufPath)
const Message = root.lookupType(protobufMessageName)
const MessageData = Message.decode(payload)
if (to) {
return Buffer.from(JSON.stringify(MessageData.toJSON()))
try {
const root = protobuf.loadSync(protobufPath)
const Message = root.lookupType(protobufMessageName)
const MessageData = Message.decode(payload)
if (to) {
return Buffer.from(JSON.stringify(MessageData.toJSON()))
}
return MessageData
} catch (err: unknown) {
signale.warn((err as Error).message.split('\n')[0])
}
return MessageData
}
}

0 comments on commit 585203b

Please sign in to comment.