How to use the NotFound function from http-errors
Find comprehensive JavaScript http-errors.NotFound code examples handpicked from public code repositorys.
http-errors.NotFound is an error constructor function that creates an HTTP 404 error object.
93 94 95 96 97 98 99 100 101 102
The error object inherits from `createError.HttpError`. <!-- eslint-disable no-undef, no-unused-vars --> ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`.
+ 41 other calls in file
31 32 33 34 35 36 37 38 39 40
forbidden: function forbidden (message) { return new createError.Forbidden(message) }, notFound: function notFound (message) { return new createError.NotFound(message) }, methodNotAllowed: function methodNotAllowed (message) { return new createError.MethodNotAllowed(message)
+ 55 other calls in file
How does http-errors.NotFound work?
http-errors.NotFound is a constructor function in the http-errors library that creates a new error instance with a 404 status code, indicating that the requested resource could not be found on the server. The error also includes an optional message string and other optional properties.
GitHub: gardener/dashboard
43 44 45 46 47 48 49 50 51 52
}) } } function notFound (req, res, next) { next(new NotFound('The server has not found anything matching the Request-URI')) } function errorToLocals (err, req) { const { message, name, stack } = err
10 11 12 13 14 15 16 17 18
``` ### Possible Constructors ```js const err = new createError.NotFound("Error message here");//constructors for all HTTP errors ``` #### List of all constructors
+ 41 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
const createError = require("http-errors"); function getUser(id) { const user = { id: 123, name: "John Doe" }; if (id !== user.id) { throw createError.NotFound(`User with id ${id} not found`); } return user; } try { const user = getUser(456); console.log(user.name); } catch (err) { console.error(err); }
In this example, createError.NotFound is used to throw a 404 Not Found error when a user with the given ID is not found. The error message is constructed using a template string, which includes the ID that was searched for but not found. The error is then caught using a try...catch block and the error message is logged to the console.
GitHub: plkokanov/dashboard
65 66 67 68 69 70 71 72 73
async getKubeconfig ({ name, namespace }) { const secret = await this.getSecret({ name, namespace }) const kubeconfigBase64 = _.get(secret, 'data.kubeconfig') if (!kubeconfigBase64) { throw NotFound('No kubeconfig found in secret') } return decodeBase64(kubeconfigBase64) }
GitHub: bd3lage/dashboard
42 43 44 45 46 47 48 49 50 51
async getKubeconfig ({ name, namespace }) { const secret = await this.getSecret({ name, namespace }) const kubeconfigBase64 = _.get(secret, 'data.kubeconfig') if (!kubeconfigBase64) { throw NotFound('No "kubeconfig" found in secret') } const kubeconfig = parseKubeconfig(decodeBase64(kubeconfigBase64)) const authProviderName = _.get(kubeconfig, 'currentUser.auth-provider.name') const serviceaccountJsonBase64 = _.get(secret, 'data["serviceaccount.json"]')
+ 3 other calls in file
GitHub: maniacs-db/arangodb
96 97 98 99 100 101 102 103 104 105
} function checkCollection(g, collection) { if (!g[collection]) { throw Object.assign( new httperr.NotFound(errors.ERROR_ARANGO_COLLECTION_NOT_FOUND.message), {errorNum: errors.ERROR_ARANGO_COLLECTION_NOT_FOUND.code} ); } }
+ 3 other calls in file
GitHub: fega/mongo-server
139 140 141 142 143 144 145 146 147 148
/** * Check that the token is not expired and wasn't used */ const tokenObj = await MagicTokens.findOne({ token, email }); if (!tokenObj) throw new HttpError.NotFound('Token not found'); if (tokenObj.exp.getTime() < new Date().getTime()) throw new HttpError.BadRequest('Token expired'); if (Object.keys(STATUS).includes(tokenObj.status)) throw new HttpError.BadRequest('Token already used'); const user = await User.findOne({ [conf.emailField]: tokenObj.email }); if (!user) throw new HttpError.BadRequest('User is not on db anymore');
GitHub: mfolkeseth/core
67 68 69 70 71 72 73 74 75
validators.alias(pAlias); validators.name(pName); validators.type(type); } catch (error) { this._log.info(`alias:del - Validation failed - ${error.message}`); const e = new HttpError.NotFound(); end({ labels: { success: false, status: e.status } }); throw e; }
+ 3 other calls in file
122 123 124 125 126 127 128 129 130
lifetime: options.qr.emailAddressVerifyLifetime }) ) if (rowCount === 0) { throw new NotFound('Invalid or expired verificationCode') } const [{ id, encryptedEmail }] = rows
84 85 86 87 88 89 90 91 92 93
} const cloudProfiles = getCloudProfiles() const cloudProfileResource = _.find(cloudProfiles, ['metadata.name', name]) if (!cloudProfileResource) { throw new NotFound(`Cloud profile with name ${name} not found`) } const seeds = getVisibleAndNotProtectedSeeds() const cloudProfile = assignSeedsToCloudProfileIteratee(seeds)(cloudProfileResource)
+ 21 other calls in file
155 156 157 158 159 160 161 162 163 164
}; const exists = await configModel.findWithPermissions(filter, options); if (exists.length === 0) { throw new HttpErrors.NotFound(); } return true; };
+ 14 other calls in file
GitHub: RPSoftCompany/tower
741 742 743 744 745 746 747 748 749
userId: userId, }, }); if (token === undefined || token === null) { throw new HttpErrors.NotFound("Token not found"); } this.log("debug", "getTechnicalUserToken", "FINISHED");
40 41 42 43 44 45 46 47 48 49
/* User related errors */ module.exports.UserNotFound = new HTTPErrors.NotFound('User not found') module.exports.CollaboratorNotFound = new HTTPErrors.NotFound( 'Collaborator not found' ) module.exports.UserMobilePhoneNotFound = new HTTPErrors.NotFound( 'User mobile phone not found' ) module.exports.UserForbidden = new HTTPErrors.Forbidden( 'The currently authorized user is not allowed to perform this operation'
+ 713 other calls in file
7 8 9 10 11 12 13 14 15 16
return createError.TooManyRequests( 'Too many wrong password provided to the user by this ip address' ) } exports.userNotFound = () => createError.NotFound('User not found') exports.passwordIncorrect = () => createError.BadRequest('Password incorrect') exports.refreshTokenRevoked = () => createError.Forbidden('Refresh token revoked')
32 33 34 35 36 37 38 39 40
/** get parent category */ const parentCategory = (parent && (parent !== "" || parent !== " ")) ? await categoryModel.findById(parent) : undefined; /** return error if parent category was not found */ if (parent && !parentCategory) throw createError.NotFound("دسته بندی والد انتخاب شده وجود ندارد"); /** save category in database */ const category = await categoryModel.create({title, parent});
+ 14 other calls in file
158 159 160 161 162 163 164 165 166 167
/** MongoDB ObjectID validator */ const {id} = await ObjectIdValidator.validateAsync({id: ProductId}); /** get product from database */ const product = await productModel.findById(id); /** return error if product was not found */ if (!product) throw createError.NotFound("محصولی یافت نشد"); /** return product */ return product; } }
+ 4 other calls in file
133 134 135 136 137 138 139 140 141 142
} } async checkExistCategory(id) { const category = await categoryModel.findById(id); console.log(category); if (!category) throw createErrors.NotFound("the category does not exist"); return category; } async getCategoryByID(req, res, next) { try {
+ 9 other calls in file
207 208 209 210 211 212 213 214 215 216 217
} async checkExistsCategory(id) { const category = await CategoryModel.findById(id); if (!category) throw createHttpError.NotFound("category does not exist"); return category; } }
+ 8 other calls in file
GitHub: nimamleo/store
35 36 37 38 39 40 41 42 43 44
async checkOtp(req, res, next) { try { await checkOtpSchema.validateAsync(req.body); const { mobile, code } = req.body; const user = await UserModel.findOne({ mobile }); if (!user) throw createHttpError.NotFound("user not found"); if (user.otp.code != code) throw createHttpError.Unauthorized( "the sent code is not valid" );
+ 2 other calls in file
http-errors.NotFound is the most popular function in http-errors (1819 examples)