Skip to content
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

response object not passing to error handling function #1060

Open
guevarez30 opened this issue Apr 1, 2022 · 1 comment
Open

response object not passing to error handling function #1060

guevarez30 opened this issue Apr 1, 2022 · 1 comment

Comments

@guevarez30
Copy link

Sofa Configuration

useSofa({
    basePath: '/api',
    schema: schema,
    async context({ req }) {
      return {
        token: req.headers['x-api-key'],
      };
    },
    onRoute(info) {
      openApi.addRoute(info, {
        basePath: '/api',
      });
    },
    errorHandler(res, errors) {
      logErrors(errors);
      res.code(500);
      res.json(formatError(errors[0]));
    },
  });

Error:

TypeError: Cannot read properties of undefined (reading 'code')
    at errorHandler (file:///home/taylorguevarez/loads/graphql/middleware/sofa.js:27:11)
    at file:///home/taylorguevarez/loads/graphql/node_modules/sofa-api/index.mjs:477:20
    at Generator.next (<anonymous>)
    at fulfilled (/home/taylorguevarez/loads/graphql/node_modules/tslib/tslib.js:114:62)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
@guevarez30
Copy link
Author

Looked through the code and the errorHandler Function never uses the request object inside index.mjs

        if (result.errors) {
            const defaultErrorHandler = (errors) => {
                return {
                    type: 'error',
                    status: 500,
                    error: errors[0],
                };
            };
            const errorHandler = sofa.errorHandler || defaultErrorHandler;
            return errorHandler(result.errors);
        }

My solution

useSofa({
    basePath: '/api',
    schema: schema,
    async context({ req }) {
      return {
        token: req.headers['x-api-key'],
      };
    },
    onRoute(info) {
      openApi.addRoute(info, {
        basePath: '/api',
      });
    },
    errorHandler(errors) {
 /*    myErrorHandler()
        Custom function to handle errors and return object 
        {
            type:  'My error type'
            status: <my error code>, 
            error: errors[0]
         }
         
         ex: 
         { type: 'Unauthorized', status: 401, error: 'Failed Auth'}
*/
       return myErrorHandler(errors)
    },
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant