Skip to content

Instantly share code, notes, and snippets.

@hayes
Created May 30, 2021 21:05
Show Gist options
  • Save hayes/7afbc9ee119bc7467f00dfeae001595c to your computer and use it in GitHub Desktop.
Save hayes/7afbc9ee119bc7467f00dfeae001595c to your computer and use it in GitHub Desktop.
error plugin idea
class Error1() extends Error {
  error1Prop = 'error 1'
}

class Error2() extends Error {
  error2Prop = 'error 2'
}

builder.queryField('example', (t) => t.int({
  errors: [Error1, Error2],
  resolve: () => {
    const n = Math.round(Number.random() * 10)
    
    if (n === 1) {
      throw new Error1('error 1 happened');
    }
    
    if (n === 2) {
      throw new Error2('error 2 happened');
    }
    
    return n;
  },
}));

builder.objectType(Error1, {
  fields: (t) => ({
    error1Field: t.exposeString('error1Prop', {}), 
  });
});

builder.objectType(Error2, {
  fields: (t) => ({
    error2Field: t.exposeString('error2Prop', {}), 
  });
});

Produces:

type Query {
  example: QueryExampleResult
}

type QueryExampleResult {
  errors: QueryExampleErrors
  result: String
}

union QueryExampleErrors = Error1 | Error2;

type Error1 {
  error1Field: String!
}

type Error2 {
  error2Field: String!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment