Error Handling: The NxError Model
When an API request fails, the system does not just return a generic "500" status. Instead, it generates a structured NxError object that provides specific context about why the request failed.
This standardized error class extends the native JavaScript Error object, enriching it with status codes, detailed debugging messages, and metadata. Whether you are debugging a failed validation or handling a network timeout, the NxError gives you the details you need to fix it fast. 🐛
The Error Structure
Exceptions in the NX ecosystem are thrown using the NxError class. This structure is consistent across the Cloud API and the internal logic.
JSON Representation
When you encounter an error, the payload often looks like this (typically wrapped in the standard API envelope or thrown by the SDK):
{
"name": "NxError",
"code": 404,
"message": "Resource Not Found",
"detail": "The Menu Item with ID 'item_123' could not be found in this context.",
"meta": {
"resourceType": "MenuItem",
"attemptedId": "item_123"
}
}
Field Definitions
| Field | Type | Description |
|---|---|---|
| code | Number | The HTTP status code (e.g., 400, 401, 404) or specific internal error identifier. |
| message | String | A high-level, human-readable summary of the error (inherited from the standard Error class). |
| detail | String | A granular explanation of the issue. Use this for debugging or displaying specific validation feedback to users. (Also accessible as details). |
| meta | Any | An optional object containing arbitrary metadata relevant to the error (e.g., failed IDs, conflicting resource names). |
| name | String | The name of the error class, defaults to NxError but can be overridden for specific subclasses. |
TypeScript Interface
For developers integrating via TypeScript, here is the class definition and interface. Note that NxError extends the standard Error class, ensuring compatibility with standard try/catch blocks and logging tools.
export interface NxErrorParams {
code?: number;
message: string;
detail?: string;
meta?: any;
name?: string;
}
export class NxError extends Error {
code?: number;
detail?: string;
details?: string;
meta: any;
constructor(params: NxErrorParams) {
super(params.message);
Object.setPrototypeOf(this, NxError.prototype);
this.name = params?.name || this.constructor.name;
this.code = params?.code;
// 'detail' is aliased to 'details' for compatibility
this.details = params?.detail;
this.detail = params?.detail;
this.meta = params?.meta;
}
}
Best Practices
- Check the Code: Always switch logic based on the
codefield (e.g., if401, redirect to login; if429, retry later). - Log the Details: While
messageis good for UI toasters, always log thedetailandmetafields to your internal monitoring for easier debugging. - Meta Data: Do not ignore the
metafield; it often contains the specific ID of the object that caused the failure, which is critical for bulk operations.