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?