D语言新手问题 D语言抛出异常处理实例

· Created · Last modified by yunfeng~ replied at · 1366 times read
// ErrnoException 可以带错误码参数,  Exception 不带错误码
// catch注意先抓带code 的,如果处理失败,还需要抓取最基本的Exception
// 参考地址:https://dlang.org/phobos/std_exception.html#ErrnoException

@Action JSONValue cancel()
{
    import std.exception; // 引入处理异常的类 ErrnoException需要
    try{
        // 参数赋值并校验
        string order_sn = request.input("order_sn","");
        if(order_sn == ""){
            throw new ErrnoException("order_sn is empty",1000); // 带code抛出错误
            // throw new Exception("order_sn is empty"); 不带code抛出错误
        }
        string orderSn = "1234567899";
        
        CancelOrderMessage cancelOrderMessage = new CancelOrderMessage();
        cancelOrderMessage.order_sn = orderSn;
        return this.resultMessage(cancelOrderMessage);

    }catch(ErrnoException e){
        // 这个是带有code的处理
        int code = e.errno;
        return this.errorMessage(code, e.msg);
    }catch(Exception ex) {
        // 这个是不带有code的处理
        int errCode = 5000;
        return this.errorMessage(errCode, ex.msg);
    }
}
Login to reply