@nestjs/common#BadRequestException TypeScript Examples
The following examples show how to use
@nestjs/common#BadRequestException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: site.utils.ts From aqualink-app with MIT License | 7 votes |
handleDuplicateSite = (err) => {
// Unique Violation: A site already exists at these coordinates
if (err.code === '23505') {
throw new BadRequestException('A site already exists at these coordinates');
}
logger.error('An unexpected error occurred', err);
throw new InternalServerErrorException('An unexpected error occurred');
}
Example #2
Source File: AlgoController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Get('/block/:roundNumber')
@HttpCode(HttpStatus.OK)
public async getBlock(@Param() { roundNumber }: PathRountNumber) {
try {
return await this.service.getBlock(Number(roundNumber));
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
throw e;
}
throw new AlgoError(`Unexpected error occurred. Reason: ${e.message || e.response?.data || e}`, 'algo.error');
}
}
Example #3
Source File: user.controller.ts From MyAPI with MIT License | 6 votes |
@ApiOperation({ summary: 'Create a user' })
@ApiBody({ type: User, description: 'User information' })
@ApiCreatedResponse({ description: 'The user was created successfully' })
@ApiBadRequestResponse({ description: 'The user could not be created' })
@ApiForbiddenResponse({ description: 'You do not have the necessary role to perform this action'Â })
@UseGuards(RolesGuard)
@Roles(DefaultRole.Admin)
@Post()
@HttpCode(HttpStatus.CREATED)
async addUser(
@Body() user: User
): Promise<void> {
try {
user.role = new Role({ id: DefaultRole.User })
await this.userService.addUser(user)
} catch (error) {
/**
* Validate database exceptions
*/
switch(error.code) {
case POSTGRES.UNIQUE_VIOLATION:
throw new BadRequestException(ERRORS.UNIQUE_VIOLATION)
default:
this.logger.error(error.message, 'ADD_USER')
throw new BadRequestException(error.message)
}
}
}
Example #4
Source File: bad-request.filter.ts From bank-server with MIT License | 6 votes |
@Catch(BadRequestException)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(public reflector: Reflector) {}
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
let statusCode = exception.getStatus();
const r = <any>exception.getResponse();
if (_.isArray(r.message) && r.message[0] instanceof ValidationError) {
statusCode = HttpStatus.UNPROCESSABLE_ENTITY;
const validationErrors = <ValidationError[]>r.message;
this._validationFilter(validationErrors);
}
r.statusCode = statusCode;
r.error = STATUS_CODES[statusCode];
response.status(statusCode).json(r);
}
private _validationFilter(validationErrors: ValidationError[]) {
for (const validationError of validationErrors) {
for (const [constraintKey, constraint] of Object.entries(
validationError.constraints,
)) {
if (!constraint) {
// convert error message to error.fields.{key} syntax for i18n translation
validationError.constraints[constraintKey] =
'error.fields.' + _.snakeCase(constraintKey);
}
}
if (!_.isEmpty(validationError.children)) {
this._validationFilter(validationError.children);
}
}
}
}
Example #5
Source File: user.controller.ts From MyAPI with MIT License | 6 votes |
@ApiOperation({ summary: 'Add new users' })
@ApiBody({ type: User, isArray: true, description: 'Info of the users' })
@ApiCreatedResponse({ description: 'The users were created successfully' })
@ApiBadRequestResponse({ description: 'The users could not be created' })
@ApiForbiddenResponse({ description: 'You do not have the necessary role to perform this action'Â })
@UseGuards(RolesGuard)
@Roles(DefaultRole.Admin)
@Post('bulk')
@HttpCode(HttpStatus.CREATED)
async createBulk(
@Body(new ParseArrayPipe({ items: User })) users: User[]
): Promise<void> {
try {
await this.userService.addUsers(users)
} catch (error) {
/**
* Validate database exceptions
*/
switch(error.code) {
case POSTGRES.UNIQUE_VIOLATION:
throw new BadRequestException(ERRORS.UNIQUE_VIOLATION)
default:
this.logger.error(error.message, 'ADD_USERS')
throw new BadRequestException(error.message)
}
}
}
Example #6
Source File: file-not-image.exception.ts From bank-server with MIT License | 6 votes |
export class FileNotImageException extends BadRequestException {
constructor(message?: string | object | any, error?: string) {
if (message) {
super(message, error);
} else {
super('error.file.not_image');
}
}
}
Example #7
Source File: song.service.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
public async verifyMatchingService({ settings }: any): Promise<boolean> {
if (settings.matchingService !== 'spotify') {
return true;
}
if (!settings.spotifyClientId || !settings.spotifyClientSecret) {
throw new BadRequestException('Please fill in all fields')
}
const spotifyApi = new Spotify({
clientId: settings.spotifyClientId,
clientSecret: settings.spotifyClientSecret
});
try {
const { body: { access_token: accessToken } } = await spotifyApi.clientCredentialsGrant();
spotifyApi.setAccessToken(accessToken);
} catch (e) {
throw new BadRequestException('Invalid spotify credentials')
}
return spotifyApi.searchTracks('Shygirl - SLIME')
.then(() => true)
.catch(() => {
throw new BadRequestException('Invalid spotify credentials')
})
}
Example #8
Source File: validation.pipe.ts From nestjs-starter with MIT License | 6 votes |
async transform(value, metadata: ArgumentMetadata) {
if (!value) {
throw new BadRequestException('No data submitted');
}
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 BadRequestException(this.buildError(errors), 'Input data validation failed');
}
return value;
}
Example #9
Source File: alerts.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Post()
@Roles(Role.TA, Role.PROFESSOR)
async createAlert(
@Body() body: CreateAlertParams,
): Promise<CreateAlertResponse> {
const { alertType, courseId, payload, targetUserId } = body;
if (!this.alertsService.assertPayloadType(alertType, payload)) {
throw new BadRequestException(
ERROR_MESSAGES.alertController.incorrectPayload,
);
}
const anotherAlert = await AlertModel.findOne({
where: {
alertType,
userId: targetUserId,
resolved: null,
},
});
// If the same user already has an alert for this then don't create a new one
if (anotherAlert) {
throw new BadRequestException(
ERROR_MESSAGES.alertController.duplicateAlert,
);
}
const alert = await AlertModel.create({
alertType,
sent: new Date(),
userId: targetUserId,
courseId,
payload,
}).save();
return alert;
}
Example #10
Source File: tenancy-core.module.ts From nestjs-tenancy with MIT License | 6 votes |
/**
* Get the Tenant information from the request header
*
* @private
* @static
* @param {boolean} isFastifyAdaptor
* @param {Request} req
* @returns
* @memberof TenancyCoreModule
*/
private static getTenantFromSubdomain(isFastifyAdaptor: boolean, req: Request) {
let tenantId = '';
if (isFastifyAdaptor) { // For Fastify
const subdomains = this.getSubdomainsForFastify(req);
if (subdomains instanceof Array && subdomains.length > 0) {
tenantId = subdomains[subdomains.length - 1];
}
} else { // For Express - Default
// Check for multi-level subdomains and return only the first name
if (req.subdomains instanceof Array && req.subdomains.length > 0) {
tenantId = req.subdomains[req.subdomains.length - 1];
}
}
// Validate if tenant identifier token is present
if (this.isEmpty(tenantId)) {
throw new BadRequestException(`Tenant ID is mandatory`);
}
return tenantId;
}
Example #11
Source File: alerts.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch(':alertId')
@Roles(Role.STUDENT, Role.TA, Role.PROFESSOR)
async closeAlert(@Param('alertId') alertId: number): Promise<void> {
const alert = await AlertModel.findOne({
where: {
id: alertId,
},
});
if (!alert) {
throw new BadRequestException(
ERROR_MESSAGES.alertController.notActiveAlert,
);
}
alert.resolved = new Date();
await alert.save();
}
Example #12
Source File: user.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Aya Abohadima <[email protected]>
* @description check if this user follow this user id
* @param {Object} user - user he follow
* @param {String} userId - id of user followed
* @returns {boolean}
*/
async checkFollowUser(user, userId) {
if ((await this.ValidationService.checkMongooseID([userId])) === 0)
throw new HttpException('there is not correct id ', HttpStatus.FORBIDDEN);
if (!user) throw new BadRequestException('not user');
if (!user.following)
await this.userModel.updateOne({ _id: user._id }, { following: [] });
for (let i = 0; i < user.following.length; i++)
if (String(userId) === String(user.following[i])) return true;
return false;
}
Example #13
Source File: question-role.guard.ts From office-hours with GNU General Public License v3.0 | 6 votes |
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
async setupData(
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
request: any,
): Promise<{ courseId: number; user: UserModel }> {
let queueId;
if (request.params.questionId) {
const question = await QuestionModel.findOne(request.params.questionId);
if (!question) {
throw new NotFoundException(
ERROR_MESSAGES.questionRoleGuard.questionNotFound,
);
}
queueId = question.queueId;
} else if (request.body.queueId) {
// If you are creating a new question
queueId = request.body.queueId;
} else {
throw new BadRequestException(
ERROR_MESSAGES.questionRoleGuard.queueOfQuestionNotFound,
);
}
const queue = await QueueModel.findOne(queueId);
// You cannot interact with a question in a nonexistent queue
if (!queue) {
throw new NotFoundException(
ERROR_MESSAGES.questionRoleGuard.queueDoesNotExist,
);
}
const courseId = queue.courseId;
const user = await UserModel.findOne(request.user.userId, {
relations: ['courses'],
});
return { courseId, user };
}
Example #14
Source File: pins.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Nada AbdElmaboud <[email protected]>
* @description report a pin by a user
* @param {string} pinId - the id of the pin
* @param {string} userId - the id of the user
* @param {string} reason - reason why the pin has been reported
* @returns {Promise<boolean>}
*/
async reportPin(userId, pinId, reason): Promise<boolean> {
if ((await this.ValidationService.checkMongooseID([pinId, userId])) == 0) {
throw new BadRequestException('not valid id');
}
let user = await this.userModel.findById(userId, { userName: 1, email: 1 });
if (!user) {
throw new BadRequestException('not valid user');
}
await this.EmailService.sendEmail(
process.env.EMAIL,
{
pinId: pinId,
userId: userId,
userName: user.userName,
email: user.email,
reason: reason,
},
'report',
'',
);
return true;
}
Example #15
Source File: AdaController.ts From tatum-blockchain-connector with MIT License | 6 votes |
throwError(e: BlockchainError): void {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError') {
throw e;
}
throw new AdaError(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`,
'ada.error',
);
}
Example #16
Source File: pins.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Nada AbdElmaboud <[email protected]>
* @description get user saved pins
* @param {string} userId - the id of the user
* @returns {Promise<Array<object>>}
*/
async getCurrentUserSavedPins(userId): Promise<Array<object>> {
if ((await this.ValidationService.checkMongooseID([userId])) == 0) {
throw new BadRequestException('not valid id');
}
let user = await this.userModel.findById(userId, { savedPins: 1 }).lean();
if (!user) throw new NotFoundException('no such user');
let retPins = [];
for (var i = 0; i < user.savedPins.length; i++) {
let pinFound = await this.pinModel
.findById(user.savedPins[i].pinId, {
imageId: 1,
imageHeight: 1,
imageWidth: 1,
topic: 1,
})
.lean();
if (pinFound) {
retPins.push(pinFound);
}
}
return retPins;
}
Example #17
Source File: AlgoController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Get('/transactions/:from/:to')
public async getPayTransactions(@Param() {from, to}: PathFromTo, @Query() {limit, next}: Pagination) {
try {
return await this.service.getPayTransactions(from, to, limit, next);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
throw e;
}
throw new AlgoError(`Unexpected error occurred. Reason: ${e.message || e.response?.data || e}`, 'algo.error');
}
}
Example #18
Source File: pins.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Nada AbdElmaboud <[email protected]>
* @description get user pins
* @param {string} userId - the id of the user
* @param {boolean} ifMe - flag indicates if current user or another user
* @param {number} limit - the limit of user pins returned
* @returns {Promise<Array<object>}
*/
async getCurrentUserPins(userId, ifMe, limit, isFollow): Promise<Array<pin>> {
if ((await this.ValidationService.checkMongooseID([userId])) == 0) {
throw new BadRequestException('not valid Id');
}
let user;
if (ifMe == true)
user = await this.userModel.findById(userId, { pins: 1 }).lean();
else user = await this.userModel.findById(userId, { pins: 1, email: 1 });
if (!user) throw new BadRequestException('no such user');
if (!ifMe && !isFollow && user.email == process.env.ADMIN_EMAIL) {
return [];
}
let retPins = [];
if (!limit || limit > user.pins.length) limit = user.pins.length;
for (var i = user.pins.length - 1; i >= user.pins.length - limit; i--) {
let pinFound = await this.pinModel.findById(user.pins[i].pinId, {
_id: 1,
imageId: 1,
imageWidth: 1,
imageHeight: 1,
title: 1,
topic: 1,
});
if (pinFound) {
retPins.push(pinFound);
}
}
return retPins;
}
Example #19
Source File: AlgoController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Get('/node/indexer/:key/*')
@HttpCode(HttpStatus.OK)
public async nodeGetIndexer(@Req() req: Request, @Param() param: { key: string }) {
try {
return await this.service.nodeMethod(req, param.key, AlgoNodeType.INDEXER);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
throw e;
}
throw new AlgoError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'Algo.error');
}
}
Example #20
Source File: images.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Nada AbdElmaboud <[email protected]>
* @description upload an image file to google drive
* @param {string} fileName - the id of the file
* @param {string} mimeType - the type of the file
* @param {Buffer} stream - the buffer of the file data
* @returns {Promise<Array<object>>}
*/
async uploadFile(fileName, mimeType, stream) {
const readable = new Readable();
readable._read = () => {};
readable.push(stream);
readable.push(null);
var fileMetadata = {
name: fileName,
};
var media = {
mimeType: mimeType,
body: readable,
};
let res = await this.drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id',
});
if (res) {
return [{ id: res.data.id }];
} else {
throw new BadRequestException();
}
}
Example #21
Source File: AlgoController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Post('/node/indexer/:key/*')
@HttpCode(HttpStatus.OK)
public async nodePostIndexer(@Req() req: Request, @Param() param: { key: string }) {
try {
return await this.service.nodeMethod(req, param.key, AlgoNodeType.INDEXER);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
throw e;
}
throw new AlgoError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'Algo.error');
}
}
Example #22
Source File: board.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Nada AbdElmaboud <[email protected]>
* @description check if board has section
* @param {board} board
* @param {string} sectionId - the id of the section
* @returns {Promise<boolean>}
*/
async checkBoardHasSection(board, sectionId): Promise<Boolean> {
if ((await this.ValidationService.checkMongooseID([sectionId])) == 0) {
throw new BadRequestException('not valid section id');
}
for (let i = 0; i < board.sections.length; i++) {
if (String(board.sections[i]._id) == String(sectionId)) {
return true;
}
}
return false;
}
Example #23
Source File: AlgoController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Post('/broadcast')
@HttpCode(HttpStatus.OK)
public async broadcast(@Body() body: BroadcastTx) {
try {
return await this.service.broadcast(body.txData, body.signatureId);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
throw e;
}
throw new AlgoError(`Unexpected error occurred. Reason: ${e.message || e.response?.data || e}`, 'algo.error');
}
}
Example #24
Source File: card.repository.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
async useCard(id: number): Promise<Card> {
const card = await this.findOne(id);
if (!card) throw new NotFoundException();
if (card.getStatus()) throw new BadRequestException();
const usingCard = (
await this.find({
where: { using: true, type: card.getType() },
})
).length;
if (usingCard >= 150 && card.getType() == 0)
throw new BadRequestException();
if (usingCard >= 150 && card.getType() == 1)
throw new BadRequestException();
card.useCard();
await this.save(card);
return card;
}
Example #25
Source File: KcsController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Post('/broadcast')
@HttpCode(HttpStatus.OK)
public async broadcast(@Body() body: BroadcastTx) {
try {
return await this.service.broadcast(body.txData, body.signatureId);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === KcsError.name) {
throw e;
}
throw new KcsError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'kcs.error');
}
}
Example #26
Source File: user.repository.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
async setCard(id: number, card: Card): Promise<User> {
// this.logger.log('setting Card Start');
// this.logger.log('_id, cardId : ', id, card.getId());
const user = await this.findWithCard(id);
if (user.getCard()) throw new BadRequestException();
user.cardSet(card);
await this.save(user);
return user;
}
Example #27
Source File: KcsController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Post('/gas')
@HttpCode(HttpStatus.OK)
public async estimateGas(@Body() body: EstimateGas) {
try {
return await this.service.estimateGas(body);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === KcsError.name) {
throw e;
}
throw new KcsError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'kcs.error');
}
}
Example #28
Source File: waiting.service.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
async create(id: number, type: number) {
const user = await this.userRepository.findOne(id);
const exist = await this.waitingRepository.find({
relations: ['user'],
where: { user: { _id: id }, deleteType: null },
});
if (exist.length > 0) throw new BadRequestException();
const waiting = new Waiting(user, type);
this.waitingRepository.save(waiting);
}
Example #29
Source File: KcsController.ts From tatum-blockchain-connector with MIT License | 6 votes |
@Post('/transaction')
@HttpCode(HttpStatus.OK)
public async sendTransaction(@Body() body: TransferErc20) {
try {
return await this.service.sendKCS(body);
} catch (e) {
if (['Array', 'ValidationError'].includes(e.constructor.name)) {
throw new BadRequestException(e);
}
if (e.constructor.name === 'TatumError' || e.constructor.name === KcsError.name) {
throw e;
}
throw new KcsError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'kcs.error');
}
}