How to use the @nestjs/common.HttpStatus.BAD_REQUEST function in @nestjs/common

To help you get started, weโ€™ve selected a few @nestjs/common examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lujakob / nestjs-realworld-example-app / src / user / user.service.ts View on Github external
async create(dto: CreateUserDto): Promise {

    // check uniqueness of username/email
    const {username, email, password} = dto;
    const qb = await getRepository(UserEntity)
      .createQueryBuilder('user')
      .where('user.username = :username', { username })
      .orWhere('user.email = :email', { email });

    const user = await qb.getOne();

    if (user) {
      const errors = {username: 'Username and email must be unique.'};
      throw new HttpException({message: 'Input data validation failed', errors}, HttpStatus.BAD_REQUEST);

    }

    // create new user
    let newUser = new UserEntity();
    newUser.username = username;
    newUser.email = email;
    newUser.password = password;
    newUser.articles = [];

    const errors = await validate(newUser);
    if (errors.length > 0) {
      const _errors = {username: 'Userinput is not valid.'};
      throw new HttpException({message: 'Input data validation failed', _errors}, HttpStatus.BAD_REQUEST);

    } else {
github xmlking / ngx-starter-kit / apps / api / src / app / external / kubernetes / kubernetes.service.ts View on Github external
private handleError(error: Error & { code?: number; statusCode?: number }) {
    const message = error.message || 'unknown error';
    const statusCode = error.statusCode || error.code || HttpStatus.I_AM_A_TEAPOT;
    console.log(message, statusCode);
    switch (statusCode) {
      case HttpStatus.CONFLICT:
        throw new ConflictException(error.message);
      case HttpStatus.UNAUTHORIZED:
        throw new UnauthorizedException(error.message);
      case HttpStatus.NOT_FOUND:
        throw new NotFoundException(error.message);
      case HttpStatus.BAD_REQUEST:
        throw new BadRequestException(error.message);
      default:
        throw new HttpException(message, statusCode);
    }
  }
}
github backstopmedia / nest-book-example / universal / src / server / modules / heroes / heroes.controller.ts View on Github external
async createHero(@Body() body) {
    if (!body || !body.name) {
      throw new HttpException('Missing hero name', HttpStatus.BAD_REQUEST);
    }

    return this.heroesService.createHero(body.name);
  }
github crudjs / rest-nestjs-postgres / src / validation.pipe.ts View on Github external
async transform(value, metadata: ArgumentMetadata) {
    const { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST);
    }
    return value;
  }
github devonfw / devon4node / template / src / shared / user / user.controller.ts View on Github external
import { User } from '../user/models';
import { getOperationId } from '../utilities/get-operation-id';
import { UserDTO, UserRole } from './models';
import { UserService } from './user.service';

@Controller('users')
@ApiUseTags('User')
@ApiBearerAuth()
export class UserController {
  constructor(private readonly _userService: UserService) {}

  @Put('update')
  @UseGuards(AuthGuard(), RolesGuard)
  @Roles(UserRole.Admin)
  @ApiResponse({ status: HttpStatus.CREATED, type: UserDTO })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiOperation(getOperationId('User', 'Update'))
  async update(@Body() userUpdate: Partial): Promise {
    try {
      const exist = await this._userService.findById(userUpdate.id);

      if (!exist) {
        throw new HttpException(
          ` This request can not be processed`,
          HttpStatus.NOT_FOUND,
        );
      }
      if (userUpdate.mail && userUpdate.mail.trim() !== '') {
        exist.mail = userUpdate.mail;
      }
      const updated = await this._userService.update(userUpdate.id, exist);
      if (updated) {
github new-eden-social / new-eden-social / packages / validation / src / validation.exception.ts View on Github external
constructor(errors: string | object | any) {
    super(
      createHttpExceptionBody(errors, 'VALIDATION_EXCEPTION', HttpStatus.BAD_REQUEST),
      HttpStatus.BAD_REQUEST,
    );
  }
}
github lonelyhentai / minellius / server / src / core / filters / custom-exception.filter.ts View on Github external
private response(
    exception: CustomValidationError | SyntaxError | Error | HttpException,
    host: ArgumentsHost,
    data: any,
    status?: number,
  ) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    Logger.error(
      JSON.stringify(exception),
      undefined,
      CustomExceptionFilter.name,
    );
    response.status(status ? status : HttpStatus.BAD_REQUEST).json(data);
  }
github new-eden-social / new-eden-social / packages / validation / src / validation.exception.ts View on Github external
constructor(errors: string | object | any) {
    super(
      createHttpExceptionBody(errors, 'VALIDATION_EXCEPTION', HttpStatus.BAD_REQUEST),
      HttpStatus.BAD_REQUEST,
    );
  }
}
github TeamHive / nestjs-seed / src / app / modules / common / exceptions / validation.exception.ts View on Github external
constructor(message?: string) {
        super(
            message || 'Request format is invalid',
            HttpStatus.BAD_REQUEST
        );
    }
}
github kelvin-mai / nest-ideas-api / src / shared / validation.pipe.ts View on Github external
async transform(value: any, metadata: ArgumentMetadata) {
    if (value instanceof Object && this.isEmpty(value)) {
      throw new HttpException(
        'Validation failed: No body submitted',
        HttpStatus.BAD_REQUEST,
      );
    }
    const { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new HttpException(
        `Validation failed: ${this.formatErrors(errors)}`,
        HttpStatus.BAD_REQUEST,
      );
    }
    return value;
  }