首页 > 解决方案 > 没有为不存在的用户获取 404 补丁

问题描述

我期望当我向不存在的用户发送补丁/更新时,我应该得到一个 404,但我得到的是一个 200。

### Update a user
PATCH http://localhost:3000/auth/2345678
Content-Type: application/json

{
  "password": "letmein"
}

HTTP/1.1 200 OK
X-Powered-By: Express
Date: Thu, 09 Sep 2021 19:41:13 GMT
Connection: close
Content-Length: 0

在控制台中,我确实回来了:

(node:36780) UnhandledPromiseRejectionWarning: NotFoundException: user not found at UsersService.update (/Users/luiscortes/Projects/car-value/src/users/users.service.ts:27:13) (node --trace-warnings ...用于显示警告的位置创建)(节点:36780)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝 id:1)(节点:36780)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。(节点:36780)UnhandledPromiseRejectionWarning:NotFoundException:在 UsersService.update 中找不到用户(/Users/luiscortes/Projects/car-value/src/users/users.service.ts:27:13)(节点:36780)UnhandledPromiseRejectionWarning:未处理承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict (请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝编号:2)

但为什么我的 REST 客户端没有 404?

这是我的users.controller.ts文件:

import {
  Body,
  Controller,
  Post,
  Get,
  Patch,
  Param,
  Query,
  Delete,
  NotFoundException,
} from '@nestjs/common';
import { CreateUserDto } from './dtos/create-user.dto';
import { UpdateUserDto } from './dtos/update-user.dto';
import { UsersService } from './users.service';

@Controller('auth')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Post('/signup')
  createUser(@Body() body: CreateUserDto) {
    this.usersService.create(body.email, body.password);
  }

  @Get('/:id')
  async findUser(@Param('id') id: string) {
    const user = await this.usersService.findOne(parseInt(id));
    if (!user) {
      throw new NotFoundException('user not foud');
    }
    return user;
  }

  @Get()
  findAllUsers(@Query('email') email: string) {
    return this.usersService.find(email);
  }

  @Delete('/:id')
  removeUser(@Param('id') id: string) {
    return this.usersService.remove(parseInt(id));
  }

  @Patch('/:id')
  updateUser(@Param('id') id: string, @Body() body: UpdateUserDto) {
    this.usersService.update(parseInt(id), body);
  }
}

这是我的users.service.ts文件:

import { Injectable, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  constructor(@InjectRepository(User) private repo: Repository<User>) {}

  create(email: string, password: string) {
    const user = this.repo.create({ email, password });

    return this.repo.save(user);
  }

  findOne(id: number) {
    return this.repo.findOne(id);
  }

  find(email: string) {
    return this.repo.find({ email });
  }

  async update(id: number, attrs: Partial<User>) {
    const user = await this.findOne(id);
    if (!user) {
      throw new NotFoundException('user not found');
    }
    Object.assign(user, attrs);
    return this.repo.save(user);
  }

  async remove(id: number) {
    const user = await this.findOne(id);
    if (!user) {
      throw new NotFoundException('user not found');
    }
    return this.repo.remove(user);
  }
}

标签: javascriptnode.jsnestjs

解决方案


您没有在路径请求中返回服务调用,因此 Nest 不知道等待它。然后,服务代码在响应发送后在后台运行,并导致这个 unhandledPromiseRejection 出现。将您的补丁方法更改为此

@Patch('/:id')
updateUser(@Param('id') id: string, @Body() body: UpdateUserDto) {
  return this.usersService.update(parseInt(id), body);
}

推荐阅读