响应和错误处理

Snowflake Native SDK for Connectors 使用某些标准响应,尤其是对于那些公开并旨在通过 UI 使用的过程。此外,它提供了一种方式,确保异常被映射为有效的响应,并记录到 EVENT TABLE 表中。

响应

SDK 过程(包括高级过程和内部过程)使用某种结构的 variant 来传递信息。对这种 variant 的要求是它必须包含一个 response_code 字段,在某些情况下,响应代码与必填字段 message 中的 OK 不同。可以包含任何其他额外字段,但需要进一步的自定义处理。THe 响应格式为:

{
    "response_code": "<response code>",
    "message": "<message>"
}
Copy

建议在替换过程和对象的默认实施时使用此格式。

错误处理

Snowflake Native SDK for Connectors 提供了一种有用的默认机制来处理运行时期间可能发生的异常。负责此操作的类称为 ConnectorErrorHelper,其默认实施为 DefaultConnectorErrorHelper。此功能提供 2 个可自定义的回调。第一个回调是 ExceptionMapper,负责将所有意外错误封装到 ConnectorException 格式中。此功能主要用于确保响应符合上述格式。

第二个回调名为 ExceptionLogger,确保错误被记录。这一点很重要,因为所有标准日志条目随后都会由 Snowflake 保存在 EVENT TABLE 中,这有助于解决应用程序的问题。

如何使用辅助程序

辅助程序公开了 2 个方法:

  • withExceptionWrapping(Supplier<ConnectorResponse> action)

  • withExceptionLogging(Supplier<T> action)

这些方法分别使用上面提到的 mapperlogger。还有一个辅助程序方法的默认实施,它将这些方法结合使用:

default ConnectorResponse withExceptionLoggingAndWrapping(Supplier<ConnectorResponse> action) {
    return withExceptionWrapping(() -> withExceptionLogging(action));
}
Copy

在从 handler 调用方法时,建议在尽可能高的层级使用这种封装。例如在 ConnectionConfigurationHandler 中,它是这样使用的:

public static Variant setConnectionConfiguration(Session session, Variant configuration) {
    var handler = ConnectionConfigurationHandler.builder(session).build();
    return handler.setConnectionConfiguration(configuration).toVariant();
}

public ConnectorResponse setConnectionConfiguration(Variant configuration) {
    return errorHelper.withExceptionLoggingAndWrapping(
        () -> setConnectionConfigurationBody(configuration)
    );
}
Copy

SDK 还公开了一个名为 ConnectorErrorHelperBuilder 的生成器来自定义此行为。此生成器允许开发者自定义 mapperlogger 回调的行为。进行自定义后,新的 helper 可以传递到各自的 buildershandler 类中。例如:

class CustomUnknownExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public ConnectorException map(Exception exception) {
        return new CustomConnectorException(exception);
    }
}

class CustomHandler {

    // Path to this method needs to be specified in the PUBLIC.SET_CONNECTION_CONFIGURATION procedure using SQL
    public static Variant configureConnection(Session session, Variant configuration) {
            //Using builder
        var errorHelper = new ConnectorErrorHelperBuilder()
            .withConnectorExceptionLogger(new CustomUnknownExceptionMapper())
            .build();

        var handler = ConnectionConfigurationHandler.builder(session)
            .withErrorHelper(errorHelper)
            .build();

        return handler.connectionConfiguration(configuration).toVariant();
    }
}
Copy
语言: 中文