Skip to content

Commit

Permalink
feat: Always preserve original messages during error serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
rekmarks committed Oct 7, 2024
1 parent 156c5c9 commit 70cc036
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
8 changes: 4 additions & 4 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ module.exports = {
// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 91.89,
functions: 94.59,
lines: 92.42,
statements: 92.42,
branches: 92.59,
functions: 94.73,
lines: 92.64,
statements: 92.64,
},
},

Expand Down
6 changes: 3 additions & 3 deletions src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ describe('serializeError', () => {
const result = serializeError(invalidError7);
expect(result).toStrictEqual({
code: rpcCodes.internal,
message: getMessageFromCode(rpcCodes.internal),
message: invalidError7.message,
data: {
cause: {
code: invalidError7.code,
Expand Down Expand Up @@ -209,7 +209,7 @@ describe('serializeError', () => {
const result = serializeError(error);
expect(result).toStrictEqual({
code: errorCodes.rpc.internal,
message: getMessageFromCode(errorCodes.rpc.internal),
message: error.message,
data: {
cause: {
message: error.message,
Expand All @@ -220,7 +220,7 @@ describe('serializeError', () => {

expect(JSON.parse(JSON.stringify(result))).toStrictEqual({
code: errorCodes.rpc.internal,
message: getMessageFromCode(errorCodes.rpc.internal),
message: error.message,
data: {
cause: {
message: error.message,
Expand Down
21 changes: 21 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,37 @@ function buildError(
return error;
}

const originalMessage = getOriginalMessage(error);

// If the error does not match the JsonRpcError type, use the fallback error, but try to include the original error as `cause`.
const cause = serializeCause(error);
const fallbackWithCause = {
...fallbackError,
...(originalMessage && { message: originalMessage }),
data: { cause },
};

return fallbackWithCause;
}

/**
* Attempts to extract the original `message` property from an error value of uncertain shape.
*
* @param error - The error in question.
* @returns The original message, if it exists and is a non-empty string.
*/
function getOriginalMessage(error: unknown): string | undefined {
if (
isObject(error) &&
hasProperty(error, 'message') &&
typeof error.message === 'string' &&
error.message.length > 0
) {
return error.message;
}
return undefined;
}

/**
* Check if the given code is a valid JSON-RPC server error code.
*
Expand Down

0 comments on commit 70cc036

Please sign in to comment.