在 Ballerina 中使用 RequestErrorInterceptor 时如何阻止 ResponseInterceptors 执行?

问题描述 投票:0回答:1

我正在寻求实现一个 RequestErrorInterceptor 来处理 RequestInterceptors 中发生的错误。但是,我注意到 ResponseInterceptors 也在执行。如何在不调用 ResponseInterceptors 的情况下实现我的要求?

在此错误拦截器中,我的目标是生成错误响应消息并阻止任何进一步的处理。这是我编写的 RequestErrorInterceptor 代码:

public isolated service class FhirRequestErrorInterceptor {
    http:RequestErrorInterceptor;

    resource isolated function 'default [string... path](http:RequestContext ctx, http:Caller caller, 
                                                        http:Request req, error err) returns http:InternalServerError {
        log:printError("HIT FhirRequestErrorInterceptor");
        http:InternalServerError errorResponse = {
            body: "FhirRequestErrorInterceptor response"
        };

        return errorResponse;
    }
}

我经历了与上面描述的相同的行为。

rest http request interceptor ballerina
1个回答
0
投票

Ballerina 中的执行顺序取决于您如何配置拦截器管道。如果您从

fhirRequestErrorInterceptor
返回有效的 HTTP 响应,它将触发管道中的任何后续响应拦截器。

以以下管道设置为例:

拦截器:[

RequestInterceptor
ResponseInterceptor1
RequestErrorInterceptor
ResponseInterceptor2
]

在此设置中,如果您的

RequestInterceptor
返回错误并且您的
RequestErrorInterceptor
返回 HTTP 响应,则会发生以下事件序列:

  1. 请求经过
    RequestInterceptor
    ,导致错误。
  2. 错误被
    RequestErrorInterceptor
    拦截,生成有效的 HTTP 响应。
  3. 返回有效响应后,控制权将转移到响应流,并触发管道下游的任何响应拦截器。
  4. 因此,响应将由
    ResponseInterceptor1
    处理。

如果我们想阻止

ResponseInterceptor1
在这种情况下被执行,你可以简单地重新排列拦截器管道,将
ResponseInterceptor1
放在
RequestErrorInterceptor
后面,如下所示:

拦截器:[

RequestInterceptor
RequestErrorInterceptor
ResponseInterceptor1
ResponseInterceptor2
]

管道顺序的调整将确保仅在有效请求通过时触发

ResponseInterceptor1
,并且在
RequestErrorInterceptor
处理错误时不会调用。

© www.soinside.com 2019 - 2024. All rights reserved.