-
Notifications
You must be signed in to change notification settings - Fork 4.3k
feat: implement standardized error handling for WhatsApp API responses #1918
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Reviewer's GuideRefactored WhatsApp API error handling by introducing a centralized formatter utility, enhancing service error propagation, and standardizing error responses in API routes. Sequence diagram for API error handling in BusinessRouter and TemplateRoutersequenceDiagram
participant Client
participant Router
participant Service
participant WhatsAppAPI
participant ErrorUtil
Client->>Router: POST /template/create (invalid data)
Router->>Service: dataValidate & createTemplate
Service->>WhatsAppAPI: requestTemplate
WhatsAppAPI-->>Service: Error response
Service-->>Router: Throws error with WhatsApp error details
Router->>ErrorUtil: createMetaErrorResponse(error, context)
ErrorUtil-->>Router: Standardized error response
Router-->>Client: HTTP 400 with MetaErrorResponse
Class diagram for standardized error handling utility and response structureclassDiagram
class MetaErrorResponse {
+number status
+string error
+string message
+details: object
+string timestamp
}
class details {
+string whatsapp_error
+string|number whatsapp_code
+string error_user_title
+string error_user_msg
+string error_type
+number|null error_subcode
+string|null fbtrace_id
+string context
+string type
}
MetaErrorResponse --> details
class createMetaErrorResponse {
+MetaErrorResponse createMetaErrorResponse(error, context)
}
createMetaErrorResponse ..> MetaErrorResponse : returns
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey there - I've reviewed your changes - here's some feedback:
- Replace all console.error calls in your catch blocks with the project’s centralized logger so that error logs remain consistent and include structured metadata like request IDs.
- Right now createMetaErrorResponse always returns HTTP 400; consider deriving the status code from the WhatsApp error code or allowing callers to override it for cases like authentication (401) or rate-limit (429) errors.
- In TemplateService, instead of rethrowing a raw Error, wrap the original error and its metadata in a custom Error subclass to preserve stack trace and ensure your error contract remains clear.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Replace all console.error calls in your catch blocks with the project’s centralized logger so that error logs remain consistent and include structured metadata like request IDs.
- Right now createMetaErrorResponse always returns HTTP 400; consider deriving the status code from the WhatsApp error code or allowing callers to override it for cases like authentication (401) or rate-limit (429) errors.
- In TemplateService, instead of rethrowing a raw Error, wrap the original error and its metadata in a custom Error subclass to preserve stack trace and ensure your error contract remains clear.
## Individual Comments
### Comment 1
<location> `src/utils/errorResponse.ts:24` </location>
<code_context>
+/**
+ * Creates standardized error response for Meta/WhatsApp API errors
+ */
+export function createMetaErrorResponse(error: any, context: string): MetaErrorResponse {
+ // Extract Meta/WhatsApp specific error fields
+ const metaError = error.template || error;
</code_context>
<issue_to_address>
The error response always uses BAD_REQUEST status, which may not fit all error scenarios.
Allow the status code to be set dynamically based on the error type, so responses can accurately reflect server or authorization errors.
Suggested implementation:
```typescript
/**
* Creates standardized error response for Meta/WhatsApp API errors
* @param error - The error object from Meta/WhatsApp API
* @param context - Context string for the error
* @param status - Optional HTTP status code (defaults to BAD_REQUEST)
* @param errorString - Optional error string (defaults to 'Bad Request')
*/
export function createMetaErrorResponse(
error: any,
context: string,
status: number = HttpStatus.BAD_REQUEST,
errorString: string = 'Bad Request'
): MetaErrorResponse {
// Extract Meta/WhatsApp specific error fields
const metaError = error.template || error;
const errorUserTitle = metaError.error_user_title || metaError.message || 'Unknown error';
const errorUserMsg = metaError.error_user_msg || metaError.message || 'Unknown error';
return {
status: status,
error: errorString,
message: errorUserTitle,
details: {
whatsapp_error: errorUserMsg,
whatsapp_code: metaError.code || 'UNKNOWN_ERROR',
```
You will need to update all usages of `createMetaErrorResponse` to optionally pass the `status` and `errorString` parameters where appropriate, e.g.:
```ts
createMetaErrorResponse(error, context, HttpStatus.UNAUTHORIZED, 'Unauthorized')
```
</issue_to_address>
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
/** | ||
* Creates standardized error response for Meta/WhatsApp API errors | ||
*/ | ||
export function createMetaErrorResponse(error: any, context: string): MetaErrorResponse { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: The error response always uses BAD_REQUEST status, which may not fit all error scenarios.
Allow the status code to be set dynamically based on the error type, so responses can accurately reflect server or authorization errors.
Suggested implementation:
/**
* Creates standardized error response for Meta/WhatsApp API errors
* @param error - The error object from Meta/WhatsApp API
* @param context - Context string for the error
* @param status - Optional HTTP status code (defaults to BAD_REQUEST)
* @param errorString - Optional error string (defaults to 'Bad Request')
*/
export function createMetaErrorResponse(
error: any,
context: string,
status: number = HttpStatus.BAD_REQUEST,
errorString: string = 'Bad Request'
): MetaErrorResponse {
// Extract Meta/WhatsApp specific error fields
const metaError = error.template || error;
const errorUserTitle = metaError.error_user_title || metaError.message || 'Unknown error';
const errorUserMsg = metaError.error_user_msg || metaError.message || 'Unknown error';
return {
status: status,
error: errorString,
message: errorUserTitle,
details: {
whatsapp_error: errorUserMsg,
whatsapp_code: metaError.code || 'UNKNOWN_ERROR',
You will need to update all usages of createMetaErrorResponse
to optionally pass the status
and errorString
parameters where appropriate, e.g.:
createMetaErrorResponse(error, context, HttpStatus.UNAUTHORIZED, 'Unauthorized')
Please fix the lint with |
the build is still failing for a different reason. The current errors are from the TypeScript compiler, not from the linter. Looking at the logs, it seems they are caused by breaking changes in a recent update of the Baileys library. |
feat: Implement standardized error handling for WhatsApp API responses
Description
This Pull Request introduces a complete refactoring of the WhatsApp API error handling to ensure that error responses are more detailed, consistent, and easier to debug. Previously, many errors from the Meta API were masked by generic messages, making it difficult to identify the root cause of issues.
What was done?
createMetaErrorResponse
, has been created insrc/utils/errorResponse.ts
. This function is responsible for taking a raw error from the WhatsApp API and transforming it into a well-structured and consistent JSON response object.TemplateService
was modified to propagate the complete error object returned by the WhatsApp API, instead of throwing a new error with a generic message. This ensures that no important details (likefbtrace_id
,error_subcode
, etc.) are lost.BusinessRouter
andTemplateRouter
were updated to usetry...catch
and call the newcreateMetaErrorResponse
function in thecatch
block. This ensures that all communication with the client follows the new error standard.Why is this necessary?
fbtrace_id
, were being discarded.How to test?
POST /template/create
) with data that you know will cause an error in the WhatsApp API (for example, an invalid component format or a template name that violates the rules).MetaErrorResponse
interface, including fields likestatus
,message
, anddetails
with specific information from the WhatsApp error.400 Bad Request
.Summary by Sourcery
Implement a consistent error-handling layer for WhatsApp API interactions by adding a formatting utility, updating service error propagation, and standardizing router error responses
Enhancements: