typeorm: Expose EntityNotFound exception

Issue type:

[ ] question [X] bug report [ ] feature request [ ] documentation issue

TypeORM version:

[X] latest

Steps to reproduce or a small repository showing the problem:

I need to check the instanceof the exception thrown:

if(exception instanceof EntityNotFound) {
// do something
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 9
  • Comments: 15 (6 by maintainers)

Most upvoted comments

It’s not exported from the global scope, but you should still be able to access it by:

import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError'

I still would love to see the error classes importable through the main package (that is not by a path inside a package). The typeorm/error/EntityNotFoundError path is not the documented way to import the error (there’s no documented way whatsoever), so it has to be considered internal implementation. And that means, it’s not subject to semver and therefore prone to unexpected changes.

To handle Typeform level exceptions with NestJs you can use the interception mechanism. The main idea is to override some DB exceptions with HTTP ones. An example can be found in the nest documentation. And there is an instruction how to bind interceptor. Finally, below you can see my implementation which potentially can override any kind of exceptions:

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
  NotFoundException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';

const errorOverridingStrategy = [
  {
    initial: EntityNotFoundError,
    target: NotFoundException,
  },
  // To support additional types of exceptions just add them to this mapping
];

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError((error) => {
        errorOverridingStrategy.forEach(({ initial, target }) => {
          if (error instanceof initial) {
            throw new target(error.message);
          }
        });
        throw error;
      }),
    );
  }
}

Thanks @Kononnable for the help!

My question: Why is QueryFailedError exported from TypeORM but EntityNotFoundError is not? Shouldn’t they both be exported from typeorm/error

Hey guys, any news here? I’m in exactly the same situation.

I’m using an exception filter from nestjs and I need to map the EntityNotFoundError to HttpNotFoundException. If the typeorm error is not exposed I have to do something like: error.constructor.name === “EntityNotFoundError”. But it would be nice to make use of the instance of operator

Isn’t this how @nestjs did it (extending Error?)