npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@actvalue/azure-errors

v1.3.0

Published

Structured logging and error handling for Azure Functions

Readme

@actvalue/azure-errors

Structured JSON logging and error handling for Azure Functions v4, designed for Application Insights consumption.

Features

  • Structured logs — every log entry is a JSON object with FunctionApp, FunctionName, InvocationId, Severity, and more
  • AsyncLocalStorage context — no need to pass InvocationContext through every function signature
  • Error hierarchyNotFoundError (404), ForbiddenError (403), BadRequestError (400) with automatic structured logging
  • HTTP error handleronError() catches any error and returns a structured HTTP response
  • Queue error handleronQueueError() logs structured errors and re-throws for Azure runtime retry/dead-lettering

Install

npm install @actvalue/azure-errors

Peer dependencies: @azure/functions ^4.0.0, applicationinsights ^2.9.0 || ^3.0.0 (optional — needed for Application Insights integration)

npm install @azure/functions applicationinsights

Quick Start

1. Set the app name and Application Insights client (once per function app)

import { setFunctionApp, setAppInsightsClient } from '@actvalue/azure-errors';
import * as appInsights from 'applicationinsights';

setFunctionApp('my-function-app');

// Optional: enable trackException for Error and Warning severity logs.
// We create a dedicated TelemetryClient instead of calling appInsights.setup().start()
// to avoid overriding the default logger and losing the host.json logging configuration.
if (process.env.APPLICATIONINSIGHTS_CONNECTION_STRING) {
  const client = new appInsights.TelemetryClient(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING);
  setAppInsightsClient(client);
}

2. Wrap handlers with runWithContext

import { HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
import { runWithContext, onError } from '@actvalue/azure-errors';

export async function myHandler(
  request: HttpRequest,
  context: InvocationContext
): Promise<HttpResponseInit> {
  try {
    return await runWithContext(context, async () => {
      // your logic here — context is available anywhere via getContext()
      return { status: 200, body: 'OK' };
    });
  } catch (error) {
    return onError(context, error);
  }
}

3. Wrap queue/timer handlers with runWithContext and onQueueError

import { InvocationContext } from '@azure/functions';
import { runWithContext, onQueueError } from '@actvalue/azure-errors';

const handler = async (message: unknown, context: InvocationContext) => {
  try {
    await runWithContext(context, async () => {
      await processMessage(message);
    });
  } catch (error) {
    onQueueError(context, error); // logs structured + re-throws
  }
};

4. Log from anywhere in the call stack

import { logInfo, logWarning, logError } from '@actvalue/azure-errors';

// No need to pass context — resolved via AsyncLocalStorage

// Pass a string code
logInfo('Processing device', deviceCode);
logWarning('DuplicateKey', 'Some records not inserted', 'CODE1');
logError('BlobStorageError', 'Write failed', mac);

// Or pass a details object
logInfo('Processing batch', { Store_id: 1, Area_id: 2 });
logWarning('DuplicateKey', 'Some records not inserted', { table: 'devices', count: 3 });
logError('BlobStorageError', 'Write failed', { container: 'images', blob: 'test.png' });

5. Throw typed errors

import { NotFoundError, ForbiddenError, BadRequestError } from '@actvalue/azure-errors';

throw new NotFoundError('Device not found', deviceCode);
// → HTTP 404, severity: Warning, structured log emitted by onError()

StructuredLog Shape

Every log entry emitted by this library follows this interface:

interface StructuredLog {
  FunctionApp: string;        // set via setFunctionApp()
  FunctionName: string;       // from InvocationContext
  InvocationId: string;       // from InvocationContext
  ErrorType: string;          // e.g. 'Info', 'NotFoundError', 'Error'
  Severity: 'Error' | 'Warning' | 'Information';
  Message: string;
  Code?: string;              // optional identifier (device code, MAC, etc.)
  Details?: Record<string, unknown>; // optional extra data
}

API

Context

| Function | Description | |----------|-------------| | runWithContext(context, fn) | Run fn with InvocationContext stored in AsyncLocalStorage | | getContext() | Retrieve the current InvocationContext (undefined outside a request) |

Logging

| Function | Description | |----------|-------------| | setFunctionApp(name) | Set the FunctionApp field for all logs | | setAppInsightsClient(client) | Enable Application Insights trackException for Error and Warning logs | | logStructured(log, context?) | Emit a full LogInput object; routes to ctx.log/warn/error by severity | | logInfo(message, codeOrDetails?) | Convenience — severity Information. Pass a string for Code or a Record<string, unknown> for Details | | logWarning(errorType, message, codeOrDetails?) | Convenience — severity Warning. Pass a string for Code or a Record<string, unknown> for Details | | logError(errorType, message, codeOrDetails?) | Convenience — severity Error. Pass a string for Code or a Record<string, unknown> for Details |

Errors

| Class | Status | Severity | |-------|--------|----------| | NotFoundError | 404 | Warning | | ForbiddenError | 403 | Warning | | BadRequestError | 400 | Warning |

| Function | Description | |----------|-------------| | onError(context, error) | HTTP catch handler — logs structured entry and returns { status, body } | | onQueueError(context, error) | Queue/timer catch handler — logs structured entry and re-throws for Azure runtime retry/dead-lettering |

Severity Routing

Logs are routed to the appropriate InvocationContext method:

| Severity | Context method | |----------|---------------| | Error | context.error() | | Warning | context.warn() | | Information | context.log() |

When no context is available (e.g. startup code), falls back to console.log.

Application Insights Integration

When an Application Insights client is configured via setAppInsightsClient(), logs with Error or Warning severity automatically call trackException. The exception is sent with the following properties:

| Property | Value | |----------|-------| | exception.name | ErrorType from the log entry | | exception.message | Message from the log entry | | properties.FunctionApp | from setFunctionApp() | | properties.FunctionName | from InvocationContext | | properties.InvocationId | from InvocationContext | | properties.Severity | Error or Warning | | properties.ErrorType | from the log entry | | properties.Code | included when provided | | properties.Details | JSON-stringified, included when provided |

Information severity logs are not sent to Application Insights.

License

Private — @actvalue