Implementing custom error handling in GraphQL using TypeORM and Apollo

Hey there, I'm currently working on implementing a custom error handling feature in my application. An example scenario is when a user tries to create an account with an email that already exists:

{
  "errors": [
    {
      "message": "The email exists",
      "statusCode": "400"
    }
  ],
  "data": null
}

Here's what I have so far:

my APP.TS:

export async function startServer() {
  const app = express();
  const schema = await createSchema();
  useContainer(Container);
  const connection = await createConnection();
  const server = new ApolloServer({
    schema,
    context: ({ req, res }: any) => ({ req, res }),
  });
  server.applyMiddleware({ app });
  return app;
}

Resovler.TS:

@Resolver()
export class CreateUserResolver {
  //dependency inject
  constructor(private readonly userService: UserService) {}

  //create User Mutaton
  @Mutation(() => User)
  async register(
    @Arg('data')
    data: RegisterInput,
  ): Promise<Partial<User> | Object> {
    const user = this.userService.findOrCreate(data);
    return user;
  }
}

Input:

@InputType()
export class RegisterInput {
  @Field()
  @IsEmail({}, { message: 'Invalid email' })
  email: string;

  @Field()
  @Length(1, 255)
  name: string;

  @Field()
  password: string;
}

Service:

constructor(
    @InjectRepository(User)
    private userRep: Repository<User>,
  ) {}

  async findOrCreate(data: Partial<User>): Promise<Partial<User> | Object> {
    let user = await this.userRep.findOne({ where: { email: data.email } });
    if (user) throw new Error('user already exists');
    data.password = await bcrypt.hash(data.password, 12);
    user = await this.userRep.save({
      ...data,
    });
    return user;
  }

Currently, my workaround is to simply use:

if (user) throw new Error ('user already exists');

However, I'm struggling to figure out how I could incorporate the status code or return only the error message without all the additional information:

https://i.sstatic.net/z7kVO.png

Answer №1

It's important to follow the proper protocol when dealing with errors in Apollo. Stick to the errors generated by Apollo as they adhere to the GraphQL standard. It's crucial to avoid displaying stacktraces to end users. To prevent stacktraces from showing in production, simply pass debug: false to the Apollo Server constructor.

For more information, visit: https://www.apollographql.com/docs/apollo-server/data/errors/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the anticipated URL and showcase the real URL

During a functional test, I am attempting to create a "Then" step where the current URL is verified. After researching on SO, it appears that the proper approach is to wait for the URL to match the expected one: Then('The URL contains {string}' ...

Implementing GetServerSideProps with Next-Auth: Error message - Trying to destructure property 'nextauth' from 'req.query' which is undefined

I encountered an issue while using the getServerSideProps function in Next.js with Next-Auth. The error I received was a TypeError: TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined. Upon checking with ...

What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API? I seem to be encountering an issue, what could I be doing wrong? getBase64Image(img) { var canvas = document.createEleme ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

How can you transform an object literal AST from a TypeScript file into executable code?

Is there a way to convert a JSON or Object Literal file into executable code? const astInJson = {"pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order {\n\torderId: string;\n\titineraries(id: string): string;\n}&b ...

Sorting mapped elements in Typescript+React: Best practices and techniques

Is there a way for me to sort the data that I retrieved using the fetch function by the value of price.amount? I know it needs to be done before mapping, but I'm unsure how to reference the amount field. I've tried looking at various tutorials, b ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

Developing a personalized validation function using Typescript for the expressValidator class - parameter is assumed to have a type of 'any'

I'm seeking to develop a unique validation function for express-validator in typescript by extending the 'body' object. After reviewing the helpful resource page, I came across this code snippet: import { ExpressValidator } from 'expre ...

Standards for coding across different languages

As I work on developing a framework that accommodates both C# and TypeScript, I am faced with an interesting dilemma. Take, for instance, the Validator class in C#: class Validator { public bool Validate(string value) { return someConditi ...

The variable 'module' is required to be of type 'any', but it is currently identified as type 'NodeModule'

I am currently working on a project using Angular and have just installed version 1.0.5 of ng2-dropdown-treeview. After installation, I restarted my server by running npm start. Upon checking the server log, I encountered the following error message: [PA ...

Creating a second optional generic parameter in TypeScript

I'm having trouble with TypeScript generics My issue is as follows: I have an interface called 'Column' and a function called makeColumn to create a new column. I want to only set the first generic (UserModel), where the accessor must be a ...

What is the solution to fixing the Vetur/Vuelidate issue where the error message "'validate' does not exist in type 'ComponentOptions<Vue [etc.]" is displayed?

QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...

Employing the Eclipse Palantir TypeScript Plug-in in conjunction with JSPM

I currently utilize the Palantir Eclipse TypeScript Plug-in (v1.8.0.v20160223-1645), which functions flawlessly when my d.ts files are stored in the same source folder /src. However, due to JSPM, these files reside in a different folder now, causing issues ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

Tips for creating fixed first two columns in a table using React and TypeScript

I need a table where the first two columns stay fixed as headers while scrolling through the body of the table. ...

Setting the TypeScript version while initializing CDK

When creating a new CDK app in typescript, I typically use the following command: npx --yes <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9babdb299e8f7e8eae1f7eb">[email protected]</a> init app --language typesc ...