Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'http-errors' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
test('It should be possible to pass a custom logger function', () => {
const expectedError = new createError.UnprocessableEntity()
const logger = jest.fn()
const handler = middy((event, context, cb) => {
throw expectedError
})
handler
.use(httpErrorHandler({ logger }))
// run the handler
handler({}, {}, (_, response) => {
expect(logger).toHaveBeenCalledWith(expectedError)
})
})
})
import HttpErrors from 'http-errors';
const A: HttpErrors.HttpError = new HttpErrors.HttpError();
const B: HttpErrors.HttpError = HttpErrors();
const C: HttpErrors.HttpError = HttpErrors(200, 'foo', {});
// $ExpectError
const D: HttpErrors.HttpError = HttpErrors('500');
const E: HttpErrors.NotFound = new HttpErrors.NotFound();
const F: HttpErrors.HttpError = new HttpErrors.LengthRequired;
const G: HttpErrors.HttpError = new HttpErrors.HttpError('foo');
(F.expose: bool);
(F.message: string);
(F.status: number);
(F.statusCode: number);
import HttpErrors from 'http-errors';
const A: HttpErrors.HttpError = new HttpErrors.HttpError();
const B: HttpErrors.HttpError = HttpErrors();
const C: HttpErrors.HttpError = HttpErrors(200, 'foo', {});
// $ExpectError
const D: HttpErrors.HttpError = HttpErrors('500');
const E: HttpErrors.NotFound = new HttpErrors.NotFound();
const F: HttpErrors.HttpError = new HttpErrors.LengthRequired;
const G: HttpErrors.HttpError = new HttpErrors.HttpError('foo');
(F.expose: bool);
(F.message: string);
(F.status: number);
(F.statusCode: number);
}
const rawBody = await readBody(req, typeInfo);
// Use the correct body parser based on Content-Type header.
switch (typeInfo.type) {
case 'application/graphql':
return { query: rawBody };
case 'application/json':
if (jsonObjRegex.test(rawBody)) {
try {
return JSON.parse(rawBody);
} catch (error) {
// Do nothing
}
}
throw httpError(400, 'POST body sent invalid JSON.');
case 'application/x-www-form-urlencoded':
return querystring.parse(rawBody);
}
// If no Content-Type header matches, parse nothing.
return {};
}
const requestHandler = (checkRequest, parseRequest) => async (req, res, next) => {
const args = checkRequest(req);
if (!args) {
next(new createError.NotFound());
return;
}
let deployment = null;
try {
deployment = await parseRequest(req.body, ...args);
if (!deployment) {
// Don't treat this as error. This simply means: We ignore the request.
res.status(201).end();
return;
}
// Finish request first
res.status(200).send('Deployment scheduled.');
} catch (error) {
console.error(error.message);
res.status(error.statusCode || 500).send({
error: error.message,
router.get('/callback', async function (ctx) {
const client = getClient();
if (!client) {
throw new ServiceUnavailable();
}
const oauth = ctx.cookies.get('oauth' + sessionSuffix);
if (!oauth) {
throw new BadRequest('Missing OAuth session');
}
ctx.cookies.set('oauth' + sessionSuffix, null);
const oauthSession = lru.get(oauth);
if (!oauthSession) {
throw new BadRequest('Invalid OAuth session');
}
const { state, nonce } = oauthSession;
let tokenSet;
try {
tokenSet = await client.authorizationCallback(
getClientRedirectURL() /* TODO: check arg */,
ctx.query,
} catch (err) {
throw createError(
400,
`Activity document could not be loaded: ${err.message}`
);
}
const activity = getActivity(store, parsed.id);
if (!activity.type || !activity.actor) {
throw createError(400, "Incomplete activity object");
}
// Verify the actor signature.
const publicKey = await signing.verify(ctx, raw, store);
if (publicKey.owner !== activity.actor) {
throw createError(400, "Signature does not match actor");
}
// Verify the activity is from the actor's origin.
if (originOf(activity.actor) !== origin) {
throw createError(400, "Activity and actor origins don't match");
}
// Load the actor document.
try {
await store.load(activity.actor);
} catch (err) {
throw createError(
400,
`Actor document could not be loaded: ${err.message}`
);
}
ctx.body = null;
return;
}
// We currently handle just 'Create'.
if (activity.type === AS("Create")) {
// The object MUST be inlined in the raw JSON, according to spec.
// This also means it was already loaded into the store.
if (typeof parsed.object !== "object") {
throw createError(400, "Invalid object in 'Create' activity");
}
const object = getObject(store, activity.object!);
if (object.type === AS("Note")) {
if (object.attributedTo !== activity.actor) {
throw createError(
400,
"Activity creates note not attributed to the actor"
);
}
// Amend object with convenience props.
const objectExt = {
...object,
actor: actor,
contentText: extractText(object.content || ""),
mentions: new Set()
};
for (const tagId of object.tags) {
// Assume these are also inlined in the JSON, and thus loaded.
// If they're not, they'll simply not pass the type check.
const tag = getTag(store, tagId);
async function all({ request, redirect, render, app }, next) {
const routes = require('../../app/routes').default; // enable hot reload server-side
let location = request.url;
let redirectLocation, renderProps;
// Use react-router match() to check if valid route
try {
[redirectLocation, renderProps] = await new Promise((res, rej) => {
match({ routes, location }, (e, ...v) => (e ? rej(e) : res(v)));
});
} catch (err) {
throw createError(500, err);
}
if (redirectLocation) {
return redirect(redirectLocation.pathname + redirectLocation.search, '/');
}
if (!renderProps) {
throw createError(404);
}
/**
* If you are NOT intersted in server-side rendering
* then replace following code with just:
*
* render(indexTpl);
*/
}
// Load the activity document.
const store = jsonld.createStore();
try {
await store.load(parsed);
} catch (err) {
throw createError(
400,
`Activity document could not be loaded: ${err.message}`
);
}
const activity = getActivity(store, parsed.id);
if (!activity.type || !activity.actor) {
throw createError(400, "Incomplete activity object");
}
// Verify the actor signature.
const publicKey = await signing.verify(ctx, raw, store);
if (publicKey.owner !== activity.actor) {
throw createError(400, "Signature does not match actor");
}
// Verify the activity is from the actor's origin.
if (originOf(activity.actor) !== origin) {
throw createError(400, "Activity and actor origins don't match");
}
// Load the actor document.
try {
await store.load(activity.actor);