How can I handle server-side errors globally in NextJS 13 with default React Error Boundary

huangapple go评论51阅读模式
英文:

How can I handle server-side errors globally in NextJS 13 with default React Error Boundary

问题

I'm very new on NextJs and I'm just started to play around directly from the latest version.
我对NextJs非常陌生,刚刚开始直接从最新版本进行试验。

I found it very interesting and enjoyable but i'm still confusing about some aspects the are clearer to me in other architectures.
我发现它非常有趣和令人愉快,但在某些方面我仍然感到困惑,这些方面在其他架构中对我来说更加清晰。

At the moment I'm tryng to understand the default Error boundary and how to leverage on it.
目前,我正在尝试理解默认的错误边界以及如何利用它。

Sice I'm bulding a full stack application, I wondering how to handle errors globally.
因为我正在构建一个全栈应用程序,我想知道如何全局处理错误。

I used to use something like Error middlewares in other frameworks but here it seems a little bit different.
在其他框架中,我曾经使用类似错误中间件的东西,但在这里似乎有点不同。

I undersud from official docs that NextJs implement React Error Boundary and all pages are wrapped on it, upon adding special file error.js (as per naming convention)
我从官方文档中了解到,NextJs实现了React错误边界,并且所有页面都包装在其中,只需添加特殊文件error.js(按命名约定)。

All clear till now, you can handle client side error like a charm but what about server side?
到目前为止一切都很清楚,你可以轻松处理客户端错误,但服务器端呢?

Reading the docs in deep I found this:
深入阅读文档后,我发现了这一点:
"If an error is thrown during data fetching or inside a Server Component, Next.js will forward the resulting Error object to the nearest error.js"

So I start make some test but it seems it doesn't work as I intended it.
所以我开始进行一些测试,但似乎不像我想象的那样工作。

Just an example:
举个例子:

Suppose you have a function Server side that retrieve some data from database.
假设你有一个服务器端函数,从数据库中检索一些数据。

That function is wrappen inside try-cacth in order to prevent unhandled exeptions.
该函数包装在try-catch中,以防止未处理的异常。

Now when I come to client side and write something like that:
现在,当我来到客户端并写了类似于以下内容的代码:

const Home=()=>{ ... throw new Error('Error') ... return{} }

its work properly and my custom error.js is renderend since it is wrapped inside React ErrorBoundary.
这样做是正确的,并且因为它包装在React错误边界中,所以我的自定义error.js会被渲染。

BUT
但是

if OI try to do that:
如果我尝试这样做:

`const Home=()=>{
     ...
     functionErrorTrigger(){
         throw new Error('Error')
     }

     ...
     return{
         <button onClick={ErrorTrigger}>ErrorTrigger<button>
     }
}`

It doesn't work, the error page is not displayed and the Exception is not graciously handled.
它不起作用,错误页面不会显示,并且异常不会被优雅地处理。

Here I'm trying to simulate for example an Error500 coming from my server.
在这里,我试图模拟例如来自我的服务器的Error500。

Im ok with the fact that the App is not crashing but I need to notificate the end user if something is not working properly in order to avoid unusefull retries.
我不介意应用程序没有崩溃,但我需要通知最终用户,如果某些事情不正常工作,以避免无用的重试。

I'm trying to figured out what i'm missing here.. definitely something dumb
我正在努力弄清楚我在这里漏掉了什么...肯定是一些愚蠢的东西。

英文:

I'm very new on NextJs and I'm just started to play around directly from the latest version.
I found it very interesting and enjoyable but i'm still confusing about some aspects the are clearer to me in other architectures.

At the moment I'm tryng to understand the default Error boundary and how to leverage on it.

Sice I'm bulding a full stack application, I wondering how to handle errors globally.
I used to use something like Error middlewares in other frameworks but here it seems a little bit different.

I undersud from official docs that NextJs implement React Error Boundary and all pages are wrapped on it, upon adding special file error.js (as per naming convention)

All clear till now, you can handle client side error like a charm but what about server side?

Reading the docs in deep I found this:
"If an error is thrown during data fetching or inside a Server Component, Next.js will forward the resulting Error object to the nearest error.js"

So I start make some test but it seems it doesn't work as I intended it.

Just an example:

Suppose you have a function Server side that retrieve some data from database.
That function is wrappen inside try-cacth in order to prevent unhandled exeptions.

Now when I come to client side and write something like that:

const Home=()=&gt;{
...
throw new Error(&#39;Error&#39;)
...
return{}
}

its work properly and my custom error.js is renderend since it is wrapped inside React ErrorBoundary.

BUT

if OI try to do that:

`const Home=()=&gt;{
     ...
     functionErrorTrigger(){
         throw new Error(&#39;Error&#39;)
     }

     ...
     return{
         &lt;button onClick={ErrorTrigger}&gt;ErrorTrigger&lt;button&gt;
     }
}`

It doesn't work, the error page is not displayed and the Exception is not graciously handled.

Here I'm trying to simulate for example an Error500 coming from my server.
Im ok with the fact that the App is not crashing but I need to notificate the end user if something is not working properly in order to avoid unusefull retries.

I'm trying to figured out what i'm missing here.. definitely something dumb

答案1

得分: 0

你应该使用 global-error.js 文件。这是一个可以在全局范围内工作的特殊的 error.js 文件。

链接:https://nextjs.org/docs/app/building-your-application/routing/error-handling#handling-errors-in-layouts

英文:

You should use global-error.js file. A special error.js file that works globally.

https://nextjs.org/docs/app/building-your-application/routing/error-handling#handling-errors-in-layouts

答案2

得分: 0

尝试将您的 error.js 更改为 not-found.js,并且不要抛出错误,而是添加:

import { notFound } from 'next/navigation';

将其添加到您的文件顶部,并使用:

function ErrorTrigger() {
  notFound();
}

https://nextjs.org/docs/app/api-reference/functions/not-found
https://nextjs.org/docs/app/api-reference/file-conventions/not-found

不幸的是,它似乎不接受错误属性,因此您无法真正通知错误的类型,但如果您只想要一个一般的“出了些问题”,这是我找到的唯一解决方法。

英文:

Try changing your error.js into not-found.js and instead of throwing an error, add:

import { notFound } from &#39;next/navigation&#39;;

To the top of your file and use:

functionErrorTrigger() {
  notFound()
}

https://nextjs.org/docs/app/api-reference/functions/not-found
https://nextjs.org/docs/app/api-reference/file-conventions/not-found

Unfortunately, it doesn't seem to take error props so you can't really notify the type of error, but if you just want a general "something went wrong" this is the only work around I've found.

huangapple
  • 本文由 发表于 2023年5月30日 00:50:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定