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 catch
ing 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
?
You aren't await
ing 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