错误码表

错误码表

方便前后台通信错误信息的统一处理,减少维护和沟通成本。例如http的statusCode,看见404 500
很容易就知道具体错误原因。

api 初步设计

interface ErrorStatus {
    code: number,
    msg: string,
}

function errorCode(code: number, msg: string): ErrorStatus {
    return { code, msg };
}

function format(errorCode, ...params): ErrorStatus  {
    const p = params.slice(0); // clone arr
    let { code, msg } = errorCode;
    msg = msg.replace(/%s/g, v => p.pop());
    return { code, msg };
}

const ErrorCodeMap = {
    SERVER_BUSY: errorCode(-1, 'server is busy'),
    OK: errorCode(0, 'OK'),
    PARAM_ERROR: errorCode(1, 'param not support for %s'),
    PERMISSION_DENIED: errorCode(2, 'permission denied'),
}

function extendErrorCodeMap(a: T, b: S): T & S {
    const result = {};
    for (let id in a) {
        (result)[id] = (a)[id];
    }
    for (let id in b) {
        if (!result.hasOwnProperty(id)) {
            (result)[id] = (b)[id];
        }
    }
    return result;
}

测试

format(ErrorCodeMap.PARAM_ERROR,'"user_id" is required');
// {code: 1, msg: "param not support for "user_id" is required"}

扩展之后可以利用ts的提示功能

let newErrorCodeMap = extendErrorCodeMap(ErrorCodeMap, {
    DELETE_ERROR: errorCode(3, 'delete error'),
});

利用typescript的提示


错误码表_第1张图片
image.png

你可能感兴趣的:(错误码表)