Error Handling
Green Dot provides a powerful error handling system that allows you to create custom errors and use them consistently throughout your application. This guide will show you how to create and use custom errors effectively.
Creating Custom Errors
Section titled “Creating Custom Errors”To create a new error file:
- Run
npx green_dot generate
- Select “Error File”
- Choose a name for your error file (e.g.,
userErrors
)
Error File Structure
Section titled “Error File Structure”Here’s an example of how to structure your error file:
import { registerErrors } from 'green_dot'
export default registerErrors({ wrongReferralCode: { code: 403 }, anyCustomError: { code: 500, anyContextualInfo: 'anyValue' },})
Thanks to this, you can now do:
throw ctx.error.anyCustomError({ anyContextualData: 'val' })// ORimport { error } from 'green_dot'throw error.anyCustomError({ anyContextualData: 'val' })
Error Context Informations
Section titled “Error Context Informations”The good practice here is to always pass any useful information to the error so it’s always easier to debug. Things like companyName, transactionId, reason or attemptedAt may be passed to an error to better track where the problem may be and what is its side effects.
- ⚠️ Be carefull not to pass sensitive data, since those data can be returned to frontend
- Always pass
code
to an error with HTTP error code good practice
Best Practices
Section titled “Best Practices”- Add Helpful Data
throw ctx.error.anyCustomError({ userId: ctx.userId, attemptedAt: new Date(), reason: ctx.reason})
- Don’t Expose Sensitive Information
// ❌ Avoidthrow ctx.error.anyCustomError({ message: `Database error: ${internalError}` })
// ✅ Goodthrow ctx.error.anyCustomError({ message: 'An error occurred while processing your request', modelName: ctx.modelName, method: ctx.method })
- Use Appropriate Status Codes
code: 404 // Not Foundcode: 403 // Forbiddencode: 400 // Bad Requestcode: 500 // Server Error