node.js - 通过 Apollo Server (NestJS) 处理异常
问题描述
有没有办法通过 apollo 异常处理程序手动运行异常?
我在 GraphQL 中有 90% 的应用程序,但仍然有两个模块作为 REST,我想统一处理异常的方式。
所以 GQL 查询抛出标准 200 错误数组,其中包含消息、扩展等。
{
"errors": [
{
"message": { "statusCode": 401, "error": "Unauthorized" },
"locations": [{ "line": 2, "column": 3 }],
"path": [ "users" ],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"response": { "statusCode": 401, "error": "Unauthorized" },
"status": 401,
"message": { "statusCode": 401, "error": "Unauthorized" }
}
}
}
],
"data": null
}
REST 使用 JSON 抛出真正的 401:
{
"statusCode": 401,
"error": "Unauthorized"
}
那么我可以简单地捕获并以 Apollo Server 格式包装异常,还是必须手动格式化我的 REST 错误?谢谢
我正在使用 NestJS 和 GraphQL 模块。
解决方案
您可以设置一个自定义异常过滤器来捕获 REST-Api 错误并将它们包装在 Apollo Server 格式中。就像是:
@Catch(RestApiError)
export class RestApiErrorFilter implements ExceptionFilter {
catch(exception: RestApiError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = 200;
response
.status(status)
.json(RestApiErrorFilter.getApolloServerFormatError(exception);
}
private static getApolloServerFormatError(exception: RestApiErrorFilter) {
return {}; // do your conversion here
}
推荐阅读
- apache-spark - 如何在 Spark 中格式化单个输出值?
- c# - 我怎样才能修复这个在运行时什么都不做的代码?
- oracle - 如何从 REST API 获取数据到 Oracle DB
- javascript - 使用带有 OOP php 类的 fetch API - 我需要 URL 吗?
- java - 创建可执行 JAR 后线程“main”java.lang.NoClassDefFoundError:org/apache/log4j/Logger 中的异常,但这是一个 JAVA 项目
- javascript - 我正在创建一个测验,但有些部分让我摸不着头脑
- oracle-sqldeveloper - 星期天出生的教职员工名单,一天的大小是9个字符长
- c# - .Net Core:从自定义异常中间件返回 IActionResult
- java - 导航视图不在工具栏内
- hyperlink -
s 使用导航时基于先前路径匹配