You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ballerina中自定义ClientError与ServiceError并处理回滚?

Ballerina中自定义ClientError和ServiceError的实现方案

Ballerina原生支持自定义错误类型,完全可以满足你定义ClientError和ServiceError并用于抛出、捕获及回滚操作的需求,具体实现方式如下:

1. 定义自定义错误类型

通过type关键字结合带标签的error类型,将两种错误声明为error的子类型,确保它们属于error体系:

// 定义客户端错误类型,绑定clientError标签
type ClientError error <clientError>;
// 定义服务端错误类型,绑定serviceError标签
type ServiceError error <serviceError>;

如果需要携带更多结构化错误信息(如错误码、详情),可以扩展错误类型的字段:

type ClientError error <clientError> {
    string message;
    int statusCode;
};

type ServiceError error <serviceError> {
    string message;
    string errorDetails;
};

2. 抛出自定义错误

在业务逻辑中,直接抛出对应类型的错误:

// 抛出ClientError
throw error(message = "客户端请求参数非法", statusCode = 400, errorType = <clientError>);

// 抛出ServiceError
throw error(message = "服务端数据库操作失败", errorDetails = "连接超时", errorType = <serviceError>);

3. 捕获错误并执行回滚

在顶层逻辑(如服务资源函数)中,通过catch语句精准捕获两种错误类型,执行回滚操作:

service /order on new http:Listener(8080) {
    resource function post /submit(http:Request req) returns http:Response {
        // 初始化事务
        transaction tx = startTransaction();
        
        try {
            validateClientInput(req); // 可能抛出ClientError
            executeServiceBusinessLogic(); // 可能抛出ServiceError
            
            // 事务提交
            commitTransaction(tx);
            return http:Response(statusCode = 200, body = "订单提交成功");
        } catch (ClientError ce) {
            // 回滚事务
            rollbackTransaction(tx);
            return http:Response(statusCode = ce.statusCode, body = ce.message);
        } catch (ServiceError se) {
            // 回滚事务
            rollbackTransaction(tx);
            return http:Response(statusCode = 500, body = se.message + ": " + se.errorDetails);
        } catch (error e) {
            // 处理其他未定义错误
            rollbackTransaction(tx);
            return http:Response(statusCode = 500, body = "未知错误");
        }
    }
}

// 校验客户端输入的函数
function validateClientInput(http:Request req) returns ClientError? {
    if req.getHeader("Content-Type") != "application/json" {
        throw error(message = "不支持的媒体类型", statusCode = 415, errorType = <clientError>);
    }
}

// 执行服务端业务逻辑的函数
function executeServiceBusinessLogic() returns ServiceError? {
    // 模拟数据库操作失败
    if databaseInsert() is error {
        throw error(message = "订单写入失败", errorDetails = "数据库连接中断", errorType = <serviceError>);
    }
}

核心优势

  • 自定义错误类型属于error体系,可无缝参与Ballerina的错误处理流程
  • 通过标签区分错误类型,捕获时能精准匹配,避免逻辑混乱
  • 支持扩展错误字段,携带业务所需的错误详情,便于问题定位

内容的提问来源于stack exchange,提问作者Nipuna Fernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:37:34