当前位置: 首页 > 编程日记 > 正文

react 错误边界_React with GraphQL和错误边界中的自定义错误页面

react 错误边界

by Abi Noda

通过Abi Noda

React with GraphQL和错误边界中的自定义错误页面 (Custom error pages in React with GraphQL and Error Boundaries)

If you like this article please support me by checking out Pull Reminders, a Slack bot that sends your team automatic reminders for GitHub pull requests.

如果您喜欢本文,请查看Pull Reminders ,这是一个Slack机器人,可以为您的团队发送有关GitHub pull请求的自动提醒,从而为我提供支持。

One challenge I recently ran into while working with GraphQL and React was how to handle errors. As developers, we’ve likely implemented default 500, 404, and 403 pages in server-rendered applications before, but figuring out how to do this with React and GraphQL is tricky.

我最近在使用GraphQL和React时遇到的一个挑战是如何处理错误。 作为开发人员,我们之前可能已经在服务器渲染的应用程序中实现了默认的500、404和403页面,但是弄清楚如何使用React和GraphQL做到这一点很棘手。

In this post, I’ll talk about how our team approached this problem, the final solution we implemented, and interesting lessons from the GraphQL spec.

在本文中,我将讨论我们的团队如何解决此问题,我们实现的最终解决方案以及GraphQL规范中有趣的课程。

背景 (Background)

The project I was working on was a fairly typical CRUD app built in React using GraphQL, Apollo Client, and express-graphQL. We wanted to handle certain types of errors — for example, the server being down — by displaying a standard error page to the user.

我正在从事的项目是使用GraphQL, Apollo Client和express-graphQL在React中构建的一个相当典型的CRUD应用程序。 我们希望通过向用户显示标准错误页面来处理某些类型的错误(例如,服务器已关闭)。

Our initial challenge was figuring out the best way to communicate errors to the client. GraphQL doesn’t use HTTP status codes like 500, 400, and 403. Instead, responses contain an errors array with a list of things that went wrong (read more about errors in the GraphQL spec).

我们最初的挑战是找出向客户传达错误的最佳方法。 GraphQL不使用500、400和403之类的HTTP状态代码。相反,响应包含一个errors数组,其中包含发生errors的列表(更多有关GraphQL规范中的 errors的信息 )。

For example, here’s what our GraphQL response looked like when something broke on the server:

例如,当服务器发生故障时,我们的GraphQL响应如下所示:

Since GraphQL error responses return HTTP status code 200, the only way to identify the kind of error was to inspect the errors array. This seemed like a poor approach because the error message property contained the exception thrown on the server. The GraphQL spec states that the value of message is intended for developers, but it does not specify whether the value should be a human-readable message or something designed to be programmatically handled:

由于GraphQL错误响应返回HTTP状态代码200,因此识别错误类型的唯一方法是检查errors数组。 这似乎是一种糟糕的方法,因为错误message属性包含在服务器上引发的异常。 GraphQL规范指出message的值是供开发人员使用的,但未指定该值是人类可读的消息还是旨在通过编程方式处理的消息:

Every error must contain an entry with the key message with a string description of the error intended for the developer as a guide to understand and correct the error.
每个错误都必须包含带有关键消息的条目,该条目带有针对开发人员的错误字符串说明,以作为开发人员理解和更正错误的指南。

将错误代码添加到GraphQL响应 (Adding Error Codes to GraphQL Responses)

To solve for this, we added standardized error codes to our error objects, which could be used by clients to programmatically identify errors. This was inspired by how Stripe’s REST API returns string error codes in addition to human-readable messages.

为了解决这个问题,我们在错误对象中添加了标准错误代码,客户端可以使用它们以编程方式识别错误。 这是受Stripe的REST API如何返回字符串错误代码以及人类可读消息的启发。

We decided on three error codes to start: authentication_error, resource_not_found, and server_error.

我们确定了要启动的三个错误代码: authentication_errorresource_not_foundserver_error

To add these to our GraphQL responses, we passed our own formatError function to express-graphql that maps exceptions thrown on the server to standard codes which get added to the response. The GraphQL spec generally discourages adding properties to error objects, but does allow for it by nesting those entries in a extensions object.

为了将这些添加到我们的GraphQL响应中,我们将自己的formatError函数传递给express-graphql,该函数将服务器上抛出的异常映射到添加到响应中的标准代码。 GraphQL规范通常不鼓励向错误对象添加属性 ,但是通过将这些条目嵌套在extensions对象中来允许这样做。

Our GraphQL response errors were then easy to classify:

然后,我们的GraphQL响应错误易于分类:

While we developed our own way of adding codes to responses generated by express-graphql, apollo-server appears to offer similar built-in behavior.

虽然我们开发了自己的方法,将代码添加到express-graphql生成的响应中,但apollo服务器似乎提供了类似的内置行为 。

使用React错误边界渲染错误页面 (Rendering error pages with React Error Boundaries)

Once we figured out a good way of handling errors in our server, we turned our attention to the client.

一旦找到了处理服务器错误的好方法,我们便将注意力转向了客户端。

By default, we wanted our app to display a global error page (for example, a page with the message “oops something went wrong”) whenever we encountered a server_error, authorization_error, or authorization_not_found. However, we also wanted the flexibility to be able to handle an error in a specific component if we wanted to.

默认情况下,当我们遇到server_errorauthorization_errorauthorization_not_found时,我们希望我们的应用程序显示一个全局错误页面(例如,显示消息“糟糕的东西出错了”的页面)。 但是,我们还希望灵活性能够在需要时处理特定组件中的错误。

For example, if a user was typing something into a search bar and something went wrong, we wanted to display an error message in-context, rather than flash over to an error page.

例如,如果用户在搜索栏中键入某些内容而出现问题,则我们希望在上下文中显示错误消息,而不是闪过错误页面。

To achieve this, we first created a component called GraphqlErrorHandler that would sit between apollo-client’s Query and Mutation components and their children to be rendered out. This component checked for error codes in the response threw an exception if it identified a code we cared about:

为此,我们首先创建了一个称为GraphqlErrorHandler的组件,该组件位于apollo-clientQueryMutation组件及其要渲染的子组件之间。 如果此组件标识了我们关心的代码,则在响应中检查错误代码会引发异常:

To use the GraphqlErrorHandler, we wrapped apollo-client’s Query and Mutation components:

为了使用GraphqlErrorHandler ,我们包装了apollo-client的QueryMutation组件:

Our feature component then used our own Query component instead of directly accessing react-apollo:

然后,我们的功能部件将使用我们自己的Query部件,而不是直接访问react-apollo

Now that our React app was throwing exceptions when the server returned errors, we wanted to handle these exceptions and map them to the appropriate behavior.

现在,当服务器返回错误时,我们的React应用程序将引发异常,我们想要处理这些异常并将它们映射到适当的行为。

Remember from earlier that our goal was to default to displaying global error pages (for example, a page with the message “oops something went wrong”), but still have the flexibility to handle an error locally within any component if we desired.

请记住,从较早时起,我们的目标是默认显示全局错误页面(例如,显示消息“哎呀,出问题了”的页面),但如果需要,仍可以灵活地在任何组件中本地处理错误。

React error boundaries provide a fantastic way of doing this. Error boundaries are React components that can catch JavaScript errors anywhere in their child component tree so you can handle them with custom behavior.

React 错误边界提供了一种出色的方法。 错误边界是React组件,可以在其子组件树的任何位置捕获JavaScript错误,因此您可以使用自定义行为来处理它们。

We created an error boundary called GraphqlErrorBoundary that would catch any server-related exceptions and display the appropriate error page:

我们创建了一个名为GraphqlErrorBoundary的错误边界,该边界将捕获与服务器相关的所有异常并显示相应的错误页面:

We use the error boundary as a wrapper for all of our app’s components:

我们将错误边界用作所有应用程序组件的包装:

Error boundaries can be used deeper in the component tree if we want to handle errors in a component instead of rendering an error page.

如果我们要处理组件中的错误而不是呈现错误页面,则可以在组件树的更深处使用错误边界。

For example, here’s what it’d look if we wanted custom error handling behavior in our component from earlier:

例如,如果我们希望早些时候在组件中实现自定义错误处理行为,就会看到以下内容:

结语 (Wrap-up)

GraphQL is still relatively new, and error handling is a common challenge that developers seem to be running into. By using standardized error codes in our GraphQL responses, we can communicate errors to clients in a useful and intuitive way. In our React apps, error boundaries provide a great way to standardize our app’s error handling behavior while still having flexibility when we need it.

GraphQL仍然相对较新,错误处理是开发人员似乎遇到的常见挑战。 通过在GraphQL响应中使用标准化的错误代码,我们可以以有用和直观的方式将错误传达给客户。 在我们的React应用程序中,错误边界提供了一种很好的方式来标准化我们应用程序的错误处理行为,同时在需要时仍具有灵活性。

翻译自: https://www.freecodecamp.org/news/how-to-handle-graphql-errors-with-react-error-boundaries-dd9273feda85/

react 错误边界

相关文章:

UITextField 限制用户输入小数点后位数的方法

UITextField 限制用户输入小数点后位数的方法 位数限制: limited 在UITextField的代理方法中添加类似如下代码 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {NSMutableString * futureStr…

[BZOJ 1002] [FJOI 2007] 轮状病毒

1002: [FJOI2007]轮状病毒 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 3045 Solved: 1687[Submit][Status][Discuss]Description 给定n(N<100)&#xff0c;编程计算有多少个不同的n轮状病毒。 Input 第一行有1个正整数n。 Output 将编程计算出的不同的n轮状病毒数输出…

微信小程序左上角返回按钮跳转到指定页面

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 在当前页面的 onUnload 执行页面跳转 onUnload: function () {wx.reLaunch({url: ../logs/logs})}, 代码讲解&#xff1a;监听页面卸载的函数&#xff0c;把页面重定向到指定的 页面&#xff1b;

过度沉思_从沉思到演出:我如何开始我的自由职业

过度沉思by Ashley MacWhirter作者&#xff1a;Ashley MacWhirter 从沉思到演出&#xff1a;我如何开始我的自由职业 (From grit to gigs: how I started my freelancing business) In less than one year, I went from a Georgia Tech Coding Bootcamp graduate to a busines…

拾人牙慧篇之———QQ微信的第三方登录实现

一、写在前面 关于qq微信登录的原理之流我就不一一赘述了&#xff0c;对应的官网都有&#xff0c;在这里主要是展示我是怎么实现出来的&#xff0c;看了好几个博客&#xff0c;有的是直接复制官网的&#xff0c;有的不知道为什么实现不了。我只能保证我的这个是我实现后才贴出来…

win7旗舰版下配置IIS服务器

选择上述的插件后&#xff0c;Windows 需要更新一段时间&#xff0c;并重启电脑 测试是否安装成功&#xff1a;http://localhost 注意&#xff1a;默认端口号是 80&#xff0c;不能和tomcat 的 80 端口同时重启 常见问题&#xff1a; 1.默认页面或者新添加的网站一直出现…

微信小程序 加载中 动画效果

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 效果图&#xff1a; 代码&#xff1a; <view class"line"><image src"../../img/line.png"></image></view>.line {height:1px;position:absolute;animat…

java开放源码_开放源码的第一周:我是如何参与的,以及我学到的东西

java开放源码by Chak Shun Yu泽顺宇 开放源码的第一周&#xff1a;我是如何参与的&#xff0c;以及我学到的东西 (My first week of open source: how I got involved, and what I’ve learned) When I started to write this post, I had finished my first serious week of …

几个不错的开源的.net界面控件

转自原文 几个不错的开源的.net界面控件 (转) 几个不错的开源的.net界面控件 - zt 介绍几个自己觉得不错的几个开源的.net界面控件&#xff0c;不知道是否有人介绍过。 DockPanel Suite&#xff1a;开发类似VS.NET的界面&#xff0c;#Develop就是使用的这个控件。 网址&#…

CSS 盒子模型(转)

CSS中&#xff0c; Box Model叫盒子模型&#xff08;或框模型&#xff09;&#xff0c;Box Model规定了元素框处理元素内容&#xff08;element content&#xff09;、内边距&#xff08;padding&#xff09;、边框&#xff08;border&#xff09; 和 外边距&#xff08;margin…

React 入门笔记 1

React的核心&#xff1a;JSX 首先&#xff0c;React 的页面就是js文件&#xff0c;看到这会有朋友疑惑了&#xff0c;js怎么写标签组件&#xff1f; 解&#xff1a;首先&#xff0c;我们需要了解JSX&#xff0c;什么是JSX&#xff1f; JSX就是JavaScript XML。一种在React组件…

自学成才翁_如何发挥自学成才的内在游戏

自学成才翁by Victor Cassone由Victor Cassone 如何发挥自学成才的内在游戏 (How to play the inner game of self-taught development) Teaching yourself software development is hard. Anyone who tells you otherwise most likely hasn’t done it before.自学软件开发非…

C语言回溯算法解决N皇后问题

回溯算法的模型是 x, not satisfy ? x-- : continue. 代码中x作列号&#xff0c;y[x]保存第x列上皇后放置的位置。 1 #include<stdio.h>2 #include<math.h>3 #define N 54 int position_check(int,int*);5 void print_board(int count,int* y);6 int main()7 {8 …

React 创建组件 使用组件 2

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 组件&#xff1a; 通过组件&#xff0c;可以将UI拆分成独立的&#xff0c;可重复使用的部分&#xff0c;从概念上讲&#xff0c;组件就像javaScript函数&#xff0c;它们接受任意输入&#xff08;称之为…

如何征服Webpack 4并构建一个出色的React应用

This article has been outdated with the new release for babel, kindly check the updated article “How to combine Webpack 4 and Babel 7 to create a fantastic React app”, last updated October 13th, 2018本文与babel的新版本已经过时&#xff0c;请查看更新的文章…

React State和生命周期 3

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 一&#xff1a;组件的生命周期 组件的生命周期可分成三个状态&#xff1a; 安装&#xff1a;已插入真实DOM更新&#xff1a;正在被重新渲染卸载&#xff1a;已移出真实DOM 生命周期的方法有&#xff1a…

TCP/IP 笔记 1.3 IP:网际协议

---恢复内容开始--- I P是T C P / I P协议族中最为核心的协议。所有的 T C P、U D P、I C M P及I G M P数据都以I P数据报格式传输。  不可靠( u n r e l i a b l e)的意思是它不能保证 I P数据报能成功地到达目的地。 I P仅提供最好的传输服务。如果发生某种错误时&#xff…

keras bi-lstm_LSTM用于文本生成的应用介绍-使用Keras和启用GPU的Kaggle Kernels

keras bi-lstmby Megan Risdal梅根里斯达尔(Megan Risdal) LSTM用于文本生成的应用介绍-使用Keras和启用GPU的Kaggle Kernels (An applied introduction to LSTMs for text generation — using Keras and GPU-enabled Kaggle Kernels) Kaggle recently gave data scientists …

201521123013 《Java程序设计》第13周学习总结

1. 本周学习总结 2. 书面作业 Q1. 网络基础 1.1 比较ping www.baidu.com与ping cec.jmu.edu.cn&#xff0c;分析返回结果有何不同&#xff1f;为什么会有这样的不同&#xff1f; ping值不同&#xff08;time列&#xff09;&#xff0c;cec.jmu.edu.cn的ping值比较小。ping值&am…

React 事件 4

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 将参数传递给事件处理程序 在循环内部&#xff0c;通常需要将额外的参数传递给事件处理程序。例如&#xff0c;如果id是行ID&#xff0c;则以下任何一个都可以工作&#xff1a; <button onClick{(e…

border-radius

周知&#xff1a;OPPO R819T Android 4.2.1和红米某些机型上&#xff0c;webview中&#xff0c;如果一个元素定义了 border border-radius&#xff0c;这时如果该元素有背景&#xff0c;那么背景将会溢出圆角之外&#xff0c;Yo新增了一个方法来fix这个问题&#xff0c;大家之…

javascript调试_如何提高JavaScript调试技能

javascript调试Almost all software developers who have written even a few lines of code for the Web have had at least a quick glance at JavaScript. After all, it is currently one of the most in-demand programming languages.几乎所有甚至为Web编写了几行代码的软…

Java transient

原文出自&#xff1a;http://www.importnew.com/21517.html 1. transient的作用及使用方法 我们都知道一个对象只要实现了Serilizable接口&#xff0c;这个对象就可以被序列化&#xff0c;java的这种序列化模式为开发者提供了很多便利&#xff0c;我们可以不必关系具体序列化的…

KBMMW 的日志管理器

kbmmw 4.82 最大的新特性就是增加了 日志管理器。 新的日志管理器实现了不同类型的日志、断言、异常处理、计时等功能。 首先。引用kbmMWLog.pas 单元后&#xff0c;系统就默认生成一个IkbmMWLog 实例&#xff1a; Log:IkbmMWLog; log 默认使用对应操作系统的日志功能。 为了能…

React 循环渲染 5

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 使用循环渲染的demo&#xff1a; const todoItems todos.map((todo) ><li key{todo.id}>{todo.text}</li> ); const todoItems todos.map((todo, index) >// Only do this if item…

面试时与人事交谈时间_如何与您的技术负责人交谈并解决通讯故障

面试时与人事交谈时间by Greg Sabo由格雷格萨博(Greg Sabo) 如何与您的技术负责人交谈并解决通讯故障 (How to talk to your tech lead and fix your communication glitches) Here’s where you messed up.这是你搞砸的地方。 Your tech lead told you to build out a new A…

inotify简介

一、inotify简介 inotify是Linux内核2.6.13 (June 18, 2005)版本新增的一个子系统&#xff08;API&#xff09;&#xff0c;它提供了一种监控文件系统&#xff08;基于inode的&#xff09;事件的机制&#xff0c;可以监控文件系统的变化如文件修改、新增、删除等&#xff0c;并…

链路层寻址与 ARP

一、 MAC 地址 不是主机或路由器具有链路层地址&#xff0c;而是它们的适配器&#xff08;即网络接口&#xff09;具有链路层地址。因此&#xff0c;具有多个网络接口的主机或路由器将具有与之相关联的多个链路层地址。 然而&#xff0c;链路层交换机并不具有与它们接口相关联的…

React 开始制作 6

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 从模拟开始 第1步&#xff1a;将UI分解为组件层次结构 不同的颜色为不同的组件&#xff0c; 第2步&#xff1a;在React中构建静态版本 第3步&#xff1a;确定UI状态的最小&#xff08;但完整&#xff…

php 空间类元素引入_引入单元素模式

php 空间类元素引入by Diego Haz迭戈哈兹(Diego Haz) 引入单元素模式 (Introducing the Single Element Pattern) 使用React和其他基于组件的库创建可靠的构建基块的规则和最佳实践。 (Rules and best practices for creating reliable building blocks with React and other …