Skip to content

Commit

Permalink
Fix/error handling and message (#809)
Browse files Browse the repository at this point in the history
* chore:handle non json error

* chore: change error message

* chore: increase message history length
  • Loading branch information
KannuSingh authored Jan 23, 2025
1 parent 536756b commit c5dc117
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const MAX_MESSAGE_LENGTH = 300;
/**
* Maximum allowed number of messages in history to prevent memory issues
*/
const MAX_HISTORY_LENGTH = 6;
const MAX_HISTORY_LENGTH = 20;

/**
* Type guard to validate the structure and content of message history
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ async function handlePost(request: Request) {
return NextResponse.json(
{
status: 'error',
message: `Internal error occurred [${errorCode}]`
message: `Unable to process the request [${errorCode}]`
},
{ status: 500 }
);
Expand Down
2 changes: 1 addition & 1 deletion advanced/dapps/chat-demo-agent/src/context/ChatContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const ChatProvider: React.FC<{ children: React.ReactNode }> = ({ children
dispatch({ type: 'ADD_MESSAGE', payload: botResponse });
} catch (error) {
const errorMessage = createMessage(
`Error: ${error instanceof Error ? error.message : 'Some error occurred'}`,
`Error: ${error instanceof Error ? error.message : 'Unable to process the request'}`,
'system',
'error'
);
Expand Down
100 changes: 58 additions & 42 deletions advanced/dapps/chat-demo-agent/src/lib/chatApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,51 +19,35 @@ interface BasicResponse {

type SendMessageApiResponse = SwapResponse | BasicResponse;

export const sendChatMessageToApi = async (
messageWithContext: MessageWithContext
): Promise<{ message: string }> => {
try {
const API_URL = '/api/send-message';
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(messageWithContext),
});

if (!response.ok) {
const errorData = await response.json();
const errorMessage = errorData.message || `Failed to get response from server: ${response.status}`;
throw new Error(errorMessage);
}
// Generic function to fetch API with type-safe body
const fetchApi = async <T extends object>(
url: string,
body: T
): Promise<Response> => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});

const data: SendMessageApiResponse = await response.json();

// Handle response with a transaction link
if ('txLink' in data) {
const statusMessage = data.txLink && data.userOpHash
? `\n${hiddenTruncateUserOpHash(data.userOpHash)}View details: ${formatLink('Transaction Link', data.txLink)}`
: data.status === 'pending' && data.userOpHash
? `\nYou can check the status later using the purchase id: ${truncateUserOpHash(data.userOpHash)}`
: '';

return {
message: `${data.message}${statusMessage}`
};
}
if (!response.ok) {
throw new Error(await parseErrorResponse(response));
}

// Handle basic response
return {
message: data.message
};
return response;
};

} catch (error) {
throw new Error(
error instanceof Error
? error.message
: 'Failed to send message: Unknown error'
);
const parseErrorResponse = async (response: Response): Promise<string> => {
const errorMessage = `Failed to get response from server: ${response.status}`;

try {
const errorData = await response.json();
return errorData.message || errorMessage;
} catch {
const errorText = await response.text();
return errorText || errorMessage;
}
};

Expand All @@ -75,3 +59,35 @@ const truncateUserOpHash = (hash: string) => `<span onclick="navigator.clipboard

// Helper function to truncate hash
const hiddenTruncateUserOpHash = (hash: string) => `<span class="hidden" title="PurchaseId" >${hash}</span>`;

const formatApiResponse = (data: SendMessageApiResponse): { message: string } => {
let statusMessage = '';

if ('txLink' in data) {
statusMessage = data.txLink && data.userOpHash
? `\n${hiddenTruncateUserOpHash(data.userOpHash)}View details: ${formatLink('Transaction Link', data.txLink)}`
: data.status === 'pending' && data.userOpHash
? `\nYou can check the status later using the purchase id: ${truncateUserOpHash(data.userOpHash)}`
: '';
}

return { message: `${data.message}${statusMessage}` };
};


// Main function to send chat message to the API
export const sendChatMessageToApi = async (
messageWithContext: MessageWithContext
): Promise<{ message: string }> => {
const API_URL = '/api/send-message';

try {
const response = await fetchApi(API_URL, messageWithContext);
const data: SendMessageApiResponse = await response.json();
return formatApiResponse(data);
} catch (error) {
throw new Error(
error instanceof Error ? error.message : 'Failed to send message: Unknown error'
);
}
};

0 comments on commit c5dc117

Please sign in to comment.