Dealing with errors in NextJS when handling server-side actions

When it comes to using error boundaries in Next.js, it seems like they mainly serve as a client-side boundary for displaying fallback components or redirecting in case of failures. However, is there a similar feature available for server actions?

I'm interested in structuring my server actions so that I can throw exceptions in case of errors and handle them centrally without having to deal with every error condition inside each server action endpoint. This concept is akin to how traditional backend code is architected with middleware or something similar.

The functionality I am aiming for is to support error handling without routing all server actions through a single endpoint:

'use server'

const RPCArray = {
    GET_DATA: (args) => {
        if (!args)
            throw new Error('No good')
        return {}
    },

    PUT_DATA: (args) => {
        if (!args)
            throw new Error('No good')
        return {}
    }
}

export async function doServerRPC(which: string, ...args: any): Promise<any> {
    try {
        return RPCArray[which](args)
    } catch (e: any) {
        return {
            message: e.message || 'An unknown error ocurred'
        }
    }
}

Where client code can call:

const resp = doServerRPC('GET_DATA')

It would be ideal if this feature was integrated into the server action system without the need to funnel all server actions through a single endpoint. Although I examined error boundaries and considered if error.tsx could be relevant, it doesn't seem to fit.

Is there an alternative approach to achieving this without requiring try/catch blocks in each server action like shown in doServerRPC above?

If implementing this in Next.js is not feasible, what language features could assist in this endeavor? For instance, is it possible to register exception handlers on a per file/module basis?

Answer №1

When it comes to errors, there are two distinct categories - those that are expected and those that are uncaught. It is always best practice to handle expected errors without throwing them. Depending on the specific user flow you are working with, here are some guidelines for dealing with expected errors:

  1. Handle the response from the doServerRPC function gracefully.
'start server'

const RPCArray = {
    GET_DATA: (args) => {
        if (!args)
            return { 
               data: null, 
               message: "Something went wrong", 
               error: grpc.status.INVALID_ARGUMENT, 
               status: false
            }
        return {}
    },

    ...
}
export async function doServerRPC(action: string, ...args: any): Promise<any> {
    return RPCArray[action](args)
}
  1. On the client side, handle the response as needed.
const result = doServerRPC('GET_DATA');
if (!result.status) {
   ....
}

const {data} = result;
....

a. Consider implementing state management solutions like Redux or Zustand, and display alerts on the page to notify users of errors. Utilize appropriate status codes for a personalized experience.

b. Another approach could involve redirecting for known errors such as NOT_FOUND.

  1. For unexpected errors, utilize an error boundary for handling.

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

ng-controller does not function properly when assigned a variable as its parameter

Every time I attempt to insert a variable into the ng-controller parameter, I receive the following error message: " Error: [ng:areq] Argument 'curController' is not a function, got string <div ng-include="templates[selected-1]" ng-cont ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

Downloading Files from Mongodb Using GridFS

I am working on an application that enables users to upload and download various files. Currently, I am facing a challenge where I am able to retrieve the file from my MongoDB database and download it locally on my machine, but I am encountering difficulti ...

What causes async / await function to be executed twice?

I am currently developing a node.js application using express. In this project, I have implemented a regular router that performs the following tasks: It searches for the myID in the DB, If the myID is found, it attempts to execute the addVisit() functio ...

Dynamically assign controllers using ng-controller

My goal is to utilize the bootstrap.ui tabset feature with an array of tab settings. These settings include the name of the controller responsible for handling its contents in order to keep my 'tab-control' template clean and simple. <div tab ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

typescript event handling with oninput

When working with a slider, I am trying to detect when the user changes the value of the slider in order to display it. I have been following the tutorial at https://www.w3schools.com/howto/howto_js_rangeslider.asp. However, this code is not compatible wi ...

options for adaptive web layout

My goal is to ensure my website is responsive by utilizing HTML5, CSS3, JavaScript, and jQuery. I am facing an issue with the responsiveness of my menu in the CSS code. PRÉSENTATION OFFRES PRODUITS RÉFÉRENCE CONTACT Menu nav { ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

Remain within the confines of the bootstrap modal upon clicking the submit button

I recently set up a modal with an integrated chatbox, and I'm facing an issue where clicking the send button reloads the page instead of keeping the action within the modal itself. I believe I've almost got it right, but I can't pinpoint exa ...

Angular 2 and beyond: Refresh @Input attribute when parent's value is modified

In my development project, I encountered an issue with a parent and child component interaction. The parent component is passing an object to the child component using the @Input decorator. However, I noticed that although the child component initially r ...

Are you planning to print the JSON information?

I've been working on mastering JavaScript and decided to create a script that displays all public Facebook statuses related to a specific keyword. However, things aren't going as planned. You can find a sample URL where the JSON data is located h ...

Calculating the Mean of Two selected options in an AngularJS drop-down menu

Is there a way to dynamically calculate the average of two selected values from different select boxes and display the result in a text field without using ng change? Here's an example: HTML I: <select ng-model="box1" ng-options="item for item in ...

Developing a single source code that can be used across various platforms such as desktop, Android, and

Having a background in C++ and some knowledge of HTML, CSS, and JavaScript, I am currently working on developing a web application using Node.js and React.js. This application will be accessible through both web browsers and mobile devices. My goal is to ...

When I click on the md-select element, a superfluous "overflow-y: scroll;" gets added to the <body> of my webpage

Typically, I have the following styles on my body: element.style { -webkit-app-region: drag; } However, when I interact with a md-select element (you can observe this behavior on the provided link), additional styles are applied. element.style { -w ...

Puppeteer: How to wait for an ajax call to complete after a navigation event

When working with my code, I encounter a situation where I need to submit a form, wait for navigation, and then submit a second form. The challenge arises because before submitting the second form, some data needs to be loaded in the form using ajax. I wa ...

Unique validation for mandatory selection on changeSelected

In my Angular HTML code, I have set up a dropdown and two text-boxes. My goal is to create a feature where, if the user selects an option from the 'payable_frequency' dropdown, then either one of the 'payable_commission' fields (min or ...

The height map method for plane displacement is experiencing issues

The heightmap I have selected: Scene without grass.jpg map : Scene with grass.jpg map: https://i.sstatic.net/q6ScO.png import * as THREE from 'three'; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'; import ...

Finishing up with regular expressions

I want to create an autocomplete feature for the input field on my website. For instance, when the tab key is pressed, I want the word htt to automatically become tp:// in the input value. This autocomplete should only work if the user inputs "htt" at the ...