3

I have a simple setup where I'm calling a service method from the controller like so:

// companies.controller.ts

@Controller("company")
export class CompaniesController {
  constructor(private companiesService: CompaniesService) {}

  @Post("/:id/upload")
  @UseInterceptors(FilesInterceptor("file"))
  uploadFiles(
    @Param("id") id: string,
    @UploadedFiles() files: Array<Express.Multer.File>,
  ) {
    // throw new HttpException("Company not found", HttpStatus.NOT_ACCEPTABLE);
    // console.log(files);
    try {
      this.companiesService.uploadFiles(id, files);
      console.log("didn't get error");
    } catch (error) {
      console.log("got error");
      throw new HttpException("forbidden", HttpStatus.FORBIDDEN);
    }
  }
}

// companies.service.ts

@Injectable()
export class CompaniesService {
  constructor(
    private prisma: PrismaService,
    private s3Service: S3Service,
    private filesService: FilesService,
  ) {}

  async uploadFiles(id: Company["id"], files: Array<Express.Multer.File>) {
    const company = false // for testing

    if (!company) {
      console.log("Company not found");
      throw new Error();
    }
}

I'm running this by using nest start --watch.

When I call this endpoint, My app quits and I get the following logged to my console:

didn't get error
Company not found

/src/companies/companies.service.ts:54
      throw new Error();
            ^
Error: 
    at CompaniesService.uploadFiles (/src/companies/companies.service.ts:54:13)

How come I can't catch the error I'm throwing in my controller? It's clearly not catching because it's logging company not found. Exception Filtering is supposed to be built in by default so I'm not sure why this isn't producing a 500?

1 Answer 1

8

You aren't awaiting the this.companiesService.uploadFiles(id, files); call, which means that it is an unhandled promise. If anything errors from it, it's an unhandled rejection. Just add async to the uploadFiles in the controller and await to thethis.companiesService.uploadFiles call and you should be good to go

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was it! I knew it had to be something silly I was missing. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.