Question3r
Question3r

Reputation: 3752

do NestJs or TypeScript provide premade exceptions like 'KeyNotFoundException'

I would like to create a NestJs backend and started with some REST endpoints but would like to support GraphQL later on too.

Let's assume I want to delete a user by id. The service layer knows if that user was deleted by checking the amount of deleted rows. If it's not zero, the user was deleted. If it's zero I want to throw a "Not found exception".

I know that Nest ships with some premade http exceptions https://docs.nestjs.com/exception-filters#built-in-http-exceptions. But I don't want to use those exceptions in my service layer because I think they should only be used in the HTTP layer (REST controllers).

So I created my own exceptions

export class KeyNotFoundException extends Error {
  constructor(message: string) {
    super(message);
  }
}

and use them in my service layer and maybe repository layer too.

public async deleteUserById(id: number): Promise<void> {
  const deletedRows: number = await this.usersRepository.deleteUserById(id);

  if (deletedRows === 0) {
    // my custom exception
    throw new KeyNotFoundException(`User with Id ${id} not found`);
  }
}

The controller could deal with this exception and throw a 404 or 500 if the error is not a KeyNotFoundException

@Delete(':id')
public async deleteUserById(@Param('id', ParseIntPipe) id: number): Promise<void> {
  try {
    await this.usersService.deleteUserById(id);
  } catch (error) {
    // my custom Exception
    if (error instanceof KeyNotFoundException) {
      // premade NestJs exception will throw 404
      throw new NotFoundException(error.message);
    }

    // premade NestJs exception will throw 500
    throw new InternalServerErrorException();
  }
}

I am not satisfied with the solution because I have translate my custom exceptions to NestJs HTTP exceptions all the time. And maybe the service could come up with multiple exceptions, I would have to use a switch to check for the correct exception type.

Are there any better ideas on how to solve this?

C# for example comes with a KeyNotFoundException but I think for TypeScript I have to create my own exception system.

Upvotes: 1

Views: 634

Answers (1)

DoronG
DoronG

Reputation: 2663

First of, I think your current solution is completely valid. If you don't want to throw http exception from the service and throw a NotFound in the controller, there is no way around converting the two. To make it easy, you can create a generic exception factory which knows how to translate your service exceptions to an http exception. You can also take care of it as part of the middleware and not worry about it on the controller side

Upvotes: 2

Related Questions