What is the best way to implement global error handling for NextJS API requests?

Is there a method to set up a Global error handler that captures the stack trace of errors and sends it to an external system like NewRelic without needing to modify each individual API? This would follow the DRY principle by avoiding changes to multiple files.

Answer №1

If you want to streamline your /api handlers, consider creating a reusable high-order function called withErrorHandler. This function can help handle errors effectively in your code.

import logger from 'some-logger';

const withErrorHandler = (handler) => async (req, res) => {
  try {
    return handler(req, res);
  } catch (error) {
    // Handle errors using the logger and customize your error response here
  }
};

Assuming your original handler function looks like this:

const handler = (req,res) => {
// Perform certain actions inside the handler
}

You can then export it with the error handling functionality like this:

export default withErrorHandler(handler)

Answer №2

class CustomError extends Error {
  constructor(errorMessage, errorCode) {
    // super is used to call the parent class constructor
    super(errorMessage);
    this.errorCode = errorCode;
    // captureStackTrace provides a string showing the error location in the call stack, aiding in pinpointing the exact error location.
    // "this" refers to the object itself, "this.constructor" indicates the constructor of this class
    Error.captureStackTrace(this, this.constructor);
  }
}

export default CustomError;

when handling routes in api

if (!user) {
    return next(new CustomError("User not found with this ID.", 400));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Angular: The Dynamic Declaration of object.property in ngModel

<input [(ngModel)]="Emp."+"dt.Rows[0]["columnname"]"> This scenario results in an undefined value In my current project, I am leveraging the power of a MVC CustomHtmlHelper to generate textboxes dynamically based on database schema. The textbox ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Enhance the readability of your Angular/Ionic applications with proper hyphenation

In my Ionic 3 app, I am using an ion-grid. Some words do not fit within the columns and are cut off, continuing on the next row without any hyphens added for proper grammar context. See image https://i.stack.imgur.com/3Q9FX.png. This layout appears quite ...

Rendering Highcharts React Pie Chart Multiple Times

Here is the code snippet: import React, { useEffect, useRef, useState } from "react"; import * as Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; export const PieChart = (props: any) =&g ...

Is VSCode spontaneously classifying the entire project as untracked without any apparent reason?

This issue could be related to extensions or the VS Code settings configuration, as I have never encountered it before. All files are being randomly listed as untracked. Current Version: 1.86.2 (Universal) To visualize the problem, here is an image: ht ...

Building a Dynamic Video Element in Next Js Using TypeScript

Is there a way to generate the video element in Next JS using TypeScript on-the-fly? When I attempt to create the video element with React.createElement('video'), it only returns a type of HTMLElement. However, I need it to be of type HTMLVideoEl ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

Create a compilation of categories/interfaces based on a mapping

Imagine you have the following object: const ROUTES = { PAGE_NO_PARAMS: '/hello/page/two', PAGE_R: '/about/:id', PAGE_Z: '/page/page/:param/:id', PAGE_N: '/who/:x/:y/:z/page', } as const Can we create a set ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

Oops! Looks like we can't find a router instance. Make sure to only utilize "next/router" on the client side of your application

Recently, I launched my app using create next app and it was functioning perfectly last night. However, today it seems to have stopped working when I try to run npm run dev for my Next.js app. Unhandled Runtime Error Error: No router instance found. ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Encountering an error stating 'ReadableStream is not defined' while attempting to log in using Discord on the NextAuth application

While attempting to set up a Discord sign-in page to test NextAuth on my website, I encountered the error ReferenceError: ReadableStream is not defined. After examining the stack trace, it seems to be related to how my packages are configured, but I' ...

How to have Angular open a PDF file in a new tab

Currently, I am working on implementing the functionality to open a PDF file in a new tab using Angular 9. The PDF file is received from an API as a blob. However, I have encountered an issue due to the deprecation of window.URL.createObjectURL(blob);. Thi ...

Create an eye-catching hexagon shape in CSS/SCSS with rounded corners, a transparent backdrop, and a

I've been working on recreating a design using HTML, CSS/SCSS in Angular. The design can be viewed here: NFT Landing Page Design Here is a snippet of the code I have implemented so far (Typescript, SCSS, HTML): [Code here] [CSS styles here] [H ...

Create a new contact in Prisma by establishing a self-referential relationship

My Prisma schema looks like this: model User { userId Int @id @default(autoincrement()) registeredAt DateTime @default(now()) firstName String @db.VarChar(250) lastName String @db.VarChar(250) email St ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Retrieving array-like form data in a TypeScript file

I need assistance with passing form inputs into a typescript file as an array in an ionic application. The form is located in question.page.html <details *ngFor="let product of products;"> <ion-input type="text" [(ngModel ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...