Error Glossary 📖
A library to centralize and craft the messages for all errors coming from Gandalf
Problem to Solve
We have several client applications using Gandalf as a BFF and a lot of the logic related services and data fetching are replicated from project to project.
This library is an attempt to centralize and reuse the same error formating logic for all the Gandalf related projects. The benefits of doing this include:
- 📒 Single source of truth for error messages on the client
- 📓 Serves as documentation for all errors related to frontend
- 🔖 Possibility to reuse messages for common errors
- ✏️ Ability to define custom errors according to the project
- ✂️ No more copy paste error handling logic when creating a new project
- 📚 Step forward to centralize and standardize errors as an organization
The last item is specially important as this is a long time proposal discussed here, with more infos here and more recently here
Installation
npm i --save @vivareal/error-glossary
yarn add @vivareal/error-glossary
Usage
Import and instantiate the ErrorGlossary
class into the file that manages graphql requests and error handling
Usually this is the lib/errors.js but if your use case is simple enough, you can plug the ErrorGlossary directly into the service.js file
import ErrorGlossary from '@vivareal/error-glossary'
const errorGlossary = new ErrorGlossary(app, options)
try {
service.graphql(...)
} catch (error) {
throw errorGlossary.getError(error);
}
Important to notice the getError
method expects an object with a property graphQLErrors
, which would be an array. Basically is what Apollo GraphQL return to the client. Errors that aren't GraphQL errors should not be passed here (Network Errors for instance), so please verify the error
object before passing to the getError
method.
Arguments
- app (string): the name of your application. Each application should have it's own glossary with formatted messages, as well as reuse common messages
app = 'CANALPRO' | 'OWNERS' | 'BACKOFFICE';
More applications can be added later
- options (object): currently the options object has only one property,
defaultError
. It will be used as a fallback in case the glossary don't find a given error from the backend
const options = {
defaultError: {
code: 'G0001',
message: 'Default Error',
statusCode: 400,
path: ['*'],
}
}
Methods
- getError: receives the graphql error object and returns the mapped error object
getError(error) {}
- isAuthError: check if the given error is an authentication error - 401
isAuthError(error) {}
- getErrorByCode(code): it returns the glossary error which matches the given code
should only be used when the APIs returns a reliable code the frontend can trust. For now, we better keep using the getError() method
getErrorByCode(code)