How to use the BadRequest function from http-errors
Find comprehensive JavaScript http-errors.BadRequest code examples handpicked from public code repositorys.
http-errors.BadRequest creates an HTTP error object representing a Bad Request (400) error.
15 16 17 18 19 20 21 22 23 24
return msg } const httpErrors = { badRequest: function badRequest (message) { return new createError.BadRequest(message) }, unauthorized: function unauthorized (message) { return new createError.Unauthorized(message)
+ 55 other calls in file
GitHub: mfolkeseth/core
138 139 140 141 142 143 144 145 146
validators.version(pVersion); validators.name(pName); validators.type(type); } catch (error) { this._log.info(`pkg:put - Validation failed - ${error.message}`); const e = new HttpError.BadRequest(); end({ labels: { success: false, status: e.status } }); throw e; }
How does http-errors.BadRequest work?
http-errors.BadRequest is a constructor function that creates an error object with a 400 status code and a default message of 'Bad Request'. It can also take an optional message parameter which is used as the error message instead of the default one. The error object created can be used in a Node.js application to indicate a client-side error where the request was malformed or invalid.
10 11 12 13 14 15 16 17 18 19
throw createError.GatewayTimeout(); } // Telegram error if (error.response && error.response.ok === false && error.response.description) { throw createError.BadRequest(error.response.description); } throw createError.InternalServerError(); }
GitHub: mfolkeseth/core
43 44 45 46 47 48 49 50 51 52
}, }); busboy.on('field', (name, value) => { if (!this._legalFields.includes(name.toLowerCase())) { busboy.emit('error', new HttpError.BadRequest()); return; } queue.push(this._handleField({
+ 3 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11
const createError = require("http-errors"); function validateUser(user) { if (!user.name) { throw new createError.BadRequest("Name is required"); } if (!user.age) { throw new createError.BadRequest("Age is required"); } // other validation logic }
In this example, http-errors.BadRequest is used to create an error object indicating that the client request was malformed due to missing required parameters. The error object can then be passed to an error handling middleware or thrown to be caught by a try-catch block.
GitHub: maniacs-db/arangodb
217 218 219 220 221 222 223 224 225 226
errors.ERROR_GRAPH_WRONG_COLLECTION_TYPE_VERTEX.code, errors.ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF.code, errors.ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS.code ].indexOf(e.errorNum) !== -1) { throw Object.assign( new httperr.BadRequest(e.errorMessage), {errorNum: e.errorNum, cause: e} ); } throw e;
104 105 106 107 108 109 110 111 112
handler: async (request, response) => { const { id } = request.authenticate() let { closeContactDate, mobile, payload } = request.body if (!validatePhone(mobile)) { throw new BadRequest( 'Supplied an incorrectly formatted phone number.' ) }
GitHub: fega/mongo-server
53 54 55 56 57 58 59 60 61
/** * Verify email and tokens */ const email = (req.body[conf.emailField] || '').toLowerCase(); if (!email) throw new HttpError.BadRequest('Missing Email'); if (!isEmail(email)) throw new HttpError.BadRequest('Invalid Email'); const tokens = await MagicTokens.find({ email, exp: { $gte: new Date() } }).toArray(); if (tokens.length >= conf.max) throw new HttpError.TooManyRequests('Token limit reached');
+ 13 other calls in file
GitHub: RPSoftCompany/tower
110 111 112 113 114 115 116 117 118 119
system = vaultConnection; } if (system === undefined || system === null) { this.log("debug", "testConnection", "FINISHED"); throw new HttpErrors.BadRequest("Vault system not configured"); } try { const resp = await axios.get(system.url);
+ 199 other calls in file
GitHub: RPSoftCompany/tower
123 124 125 126 127 128 129 130 131 132
}, }); if (exists === null) { this.log('debug', 'addGroupRole', 'FINISHED'); throw new HttpErrors.BadRequest('Invalid role name'); } if (!group.roles.includes(role)) { group.roles.push(role);
+ 24 other calls in file
GitHub: RPSoftCompany/tower
621 622 623 624 625 626 627 628 629
name: groupName, }, }); if (group === null) { throw new HttpErrors.BadRequest("Invalid group"); } user.groups.push(groupName);
+ 7 other calls in file
GitHub: nxtedition/nxt-lib
52 53 54 55 56 57 58 59 60 61
} else { reqLogger.trace('request started') } if (!ctx.url) { throw new createError.BadRequest() } await Promise.all([ new Promise((resolve, reject) => {
+ 19 other calls in file
GitHub: campsi/campsi-mono
33 34 35 36 37 38 39 40 41 42
// Is ID well-formed ? if (req.params.id) { req.filter = { _id: createObjectId(req.params.id) }; if (!req.filter._id) { throw new createError.BadRequest("Can't recognize proper id"); } } req.groups = req.query?.groups ? getValidGroupsFromString(req.query.groups) : [];
111 112 113 114 115 116 117 118 119 120
module.exports.ConflictingProductCode = new HTTPErrors.Conflict( 'A product already exists with this code' ) /* Purchase errors */ module.exports.WebhookSignatureVerificationFailed = new HTTPErrors.BadRequest( 'Webhook signature verification failed' ) module.exports.PurchaseNotFound = new HTTPErrors.NotFound('Purchase not found') module.exports.BillingAddressNotFound = new HTTPErrors.NotFound(
+ 83 other calls in file
58 59 60 61 62 63 64 65 66 67
library_page, ].forEach((page) => { if (page) { if (!isNumeric(page)) { return next( createError.BadRequest('Page should be a positive integer or 0.') ); } } });
9 10 11 12 13 14 15 16 17 18
) } exports.userNotFound = () => createError.NotFound('User not found') exports.passwordIncorrect = () => createError.BadRequest('Password incorrect') exports.refreshTokenRevoked = () => createError.Forbidden('Refresh token revoked') exports.refreshTokenMalformed = () => createError.Forbidden('Refresh token malformed')
24 25 26 27 28 29 30 31 32 33
const data = req.body const bodyLength = Object.keys(data).length const user = await knex.select('name').from('users').where('email', data.email).first() let result = '' if (!bodyLength) throw new createErrors.BadRequest('Request body empty') if (user) throw new createErrors.Conflict('Account has been registered') const hashPassword = await argon2.hash(data.password, { type: argon2.argon2id })
+ 2 other calls in file
6 7 8 9 10 11 12 13 14 15
const register = async (req, res, next) => { try { const validatedResult = await userSchema.validateAsync(req.body); const existingUser = await User.findOne({ email: validatedResult.email }) if (existingUser) throw createError.BadRequest(`${validatedResult.email} is already registered!`); const user = new User(validatedResult); const savedUser = await user.save(); const { accessToken, payload } = await signAccessToken(savedUser.id, savedUser.email);
198 199 200 201 202 203 204 205 206 207
async fetchUser(req, res, next) { try { const id = req.params.id; if (!id) { throw createError.BadRequest("Url parameter is invalid"); } else { const user = await FetchUserById(id); // console.log(user); try {
+ 3 other calls in file
GitHub: PriyankTAI/investigo
133 134 135 136 137 138 139 140 141 142 143
this.lastLogin = Date.now(); await this.save(); return token; } catch (error) { // console.log(error); throw createError.BadRequest(error); } }; // verify 2fa code
+ 15 other calls in file
16 17 18 19 20 21 22 23 24 25
req.body.image = req.body.image.replace(/\\/g, "/"); const author = req.user._id; const image = req.body.image; const existBlog = await blogModel.findOne({ title: title }); if (existBlog) throw createError.BadRequest("the blog titlt is Repetitive"); const blog = await blogModel.create({ title, text, shortText,
+ 4 other calls in file
http-errors.NotFound is the most popular function in http-errors (1819 examples)