有没有一种方法可以通过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模块。
您可以设置一个自定义exception filter,以捕获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
}