Skip to content

Commit

Permalink
misc: added metric for api errors
Browse files Browse the repository at this point in the history
  • Loading branch information
sheensantoscapadngan committed Dec 19, 2024
1 parent ce5e591 commit bbc8091
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions backend/src/server/plugins/error-handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { ForbiddenError, PureAbility } from "@casl/ability";
import opentelemetry from "@opentelemetry/api";
import fastifyPlugin from "fastify-plugin";
import jwt from "jsonwebtoken";
import { ZodError } from "zod";

import { getConfig } from "@app/lib/config/env";
import {
BadRequestError,
DatabaseError,
Expand Down Expand Up @@ -35,8 +37,30 @@ enum HttpStatusCodes {
}

export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider) => {
const appCfg = getConfig();

const apiMeter = opentelemetry.metrics.getMeter("API");
const errorHistogram = apiMeter.createHistogram("API_errors", {
description: "API errors by type, status code, and name",
unit: "1"
});

server.setErrorHandler((error, req, res) => {
req.log.error(error);
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
const { method } = req;
const route = req.routerPath;
const errorType =
error instanceof jwt.JsonWebTokenError ? "TokenError" : error.constructor.name || "UnknownError";

errorHistogram.record(1, {
route,
method,
type: errorType,
name: error.name
});
}

if (error instanceof BadRequestError) {
void res
.status(HttpStatusCodes.BadRequest)
Expand Down

0 comments on commit bbc8091

Please sign in to comment.