@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
InvocationContextthrough every function signature - Error hierarchy —
NotFoundError(404),ForbiddenError(403),BadRequestError(400) with automatic structured logging - HTTP error handler —
onError()catches any error and returns a structured HTTP response - Queue error handler —
onQueueError()logs structured errors and re-throws for Azure runtime retry/dead-lettering
Install
npm install @actvalue/azure-errorsPeer dependencies: @azure/functions ^4.0.0, applicationinsights ^2.9.0 || ^3.0.0 (optional — needed for Application Insights integration)
npm install @azure/functions applicationinsightsQuick 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
