Zzz.ZException 1.1.0

dotnet add package Zzz.ZException --version 1.1.0
                    
NuGet\Install-Package Zzz.ZException -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Zzz.ZException" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Zzz.ZException" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Zzz.ZException" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Zzz.ZException --version 1.1.0
                    
#r "nuget: Zzz.ZException, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Zzz.ZException@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Zzz.ZException&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Zzz.ZException&version=1.1.0
                    
Install as a Cake Tool

ZException

🍀项目由来

目前手上的项目需要本地化异常捕获,为解决统一异常状态码,同时需要兼容客户端多种语言;

🍀处理异常方式

  • 不处理,中断执行流程
  • 使用try catch捕获异常处理
  • 全局统一处理

🍀项目说明

当前项目用来统一拦截抛出的异常,同时根据当前语言环境改变抛出的提示消息;项目中已定义默认的错误描述单元ErrorCodeItemMetaAttribute来描述中文(简体)、英文错误;需要注意的是这里已定义的的中英文语言描述为language-script,而非language-country/region

zh-CN是language - country/region,中文-中国大陆

zh-Hans是language - script,中文-简体汉字

🍀使用

💎快速上手

1.注册
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddZException(options =>
{
    options.DefaultCode = -1;//默认错误码
    options.DefaultMessage = "出错了,请联系管理员";//默认错误
    options.HeaderLanguage = "Language";//设置请求头语言字段
});

2.定义业务错误码
/// <summary>
/// 错误示例
/// </summary>
[ErrorType]
public enum Module1Error
{
    /// <summary>
    /// 用户不存在
    /// </summary>
    [ErrorCodeItemMeta("用户不存在", "user does not exist")]
    UserError=10001
}

3.抛出异常
throw new ZException(Module1Error.UserError);
{
    "code": 10001,
    "message": "用户不存在",
    "data": null
}

💎定义

首先需要定义一个错误码的枚举类型,需要在枚举类型上加上标签[ErrorType],否则不会往下寻找错误描述,如果是中英文可以使用默认提供的[ErrorCodeItemMeta("zh-Hant", "en")]或者单独使用仅中文提示;

[ErrorType]
public enum Module1Error
{
    /// <summary>
    /// 用户不存在
    /// </summary>
    [ErrorCodeItemMeta("用户不存在", "user does not exist")]
    UserError=10001,

    /// <summary>
    /// 密码错误
    /// </summary>
    [ErrorCodeItemMeta("密码错误", "password error")]
    PwdError = 10002,

    /// <summary>
    /// 未知错误
    /// </summary>
    [ErrorCodeItemMeta("未知错误")]
    Unknow = 10003
}

💎统一异常

请求头使用Language:zh-Hans描述语言类型

//这里抛出用户不存在异常10001
throw new ZException(Module1Error.UserError);
//Language:zh-Hans结果
{
    "code": 10001,
    "message": "用户不存在",
    "data": null
}

//Language:en结果
{
    "code": 10001,
    "message": "user does not exist",
    "data": null
}

💎扩展

可以通过继承 IErrorAttribute来扩展语言支持,需要注意扩展的描述特性默认把字段的命名与请求中设置的获取语言字段的值保持一致,如请求头使用zh-Hans,描述特性中的字段因使用zh_Hans(自动替换了 '_'和'-'),以下是默认的描述特性类

/// <summary>
/// 默认错误描述元数据
/// </summary>
public class ErrorCodeItemMetaAttribute : IErrorAttribute
{
    public ErrorCodeItemMetaAttribute()
    {
    }

    public ErrorCodeItemMetaAttribute(string zh_Hans)
    {
        this.zh_Hans = zh_Hans;
    }

    public ErrorCodeItemMetaAttribute(string zh_Hans, string en)
    {
        this.zh_Hans = zh_Hans;
        this.en = en;
    }

    /// <summary>
    /// 中文(简体)
    /// </summary>
    public string zh_Hans { get; set; }

    /// <summary>
    /// 英文
    /// </summary>
    public string en { get; set; }
}

现在使用马来语作为扩展,按照规则定义一个马来语的描述,然后设置请求头的Language:ms,发送请求后抛出异常,会自动匹配到马来语的错误描述;

/// <summary>
/// 扩展(马来西亚)
/// </summary>
public class MalaysiaErrorCodeItemMetaAttribute : IErrorAttribute
{
    /// <summary>
    /// 马来语
    /// </summary>
    /// <param name="ms">马来语</param>
    /// <param name="zh_Hans">汉语</param>
    public MalaysiaErrorCodeItemMetaAttribute(string ms, string zh_Hans,string en)
    {
        this.ms = ms;
        this.zh_Hans = zh_Hans;
        this.en = en;
    }

    /// <summary>
    /// 马来语
    /// </summary>
    public string ms { get; set; }

    /// <summary>
    /// 简体中文(参数名语请求的zh-Hans对应,'_'会被'-'替换)
    /// </summary>
    public string zh_Hans { get; set; }

    /// <summary>
    /// 英语
    /// </summary>
    public string en { get; set; }
}



    /// <summary>
    /// 马来语扩展错误示例
    /// </summary>
    [ErrorType]
    public enum Module2Error
    {
        /// <summary>
        /// 用户不存在
        /// </summary>
        [MalaysiaErrorCodeItemMeta("Pengguna tidak wujud", "用户不存在", "user does not exist")]
        UserError = 10001,

        /// <summary>
        /// 密码错误
        /// </summary>
        [MalaysiaErrorCodeItemMeta("Ralat kata laluan","密码错误", "password error")]
        PwdError = 10002
    }
{
    "code": 10001,
    "message": "Pengguna tidak wujud",
    "data": null
}

💎自定义语言标识

还是以马来语作为示例,在马来语上面设置特性[LanguageDescription("Malay")],同时请求头设置Language:Malay

/// <summary>
/// 马来语
/// </summary>
[LanguageDescription("Malay")]
public string ms { get; set; }

{
    "code": 10001,
    "message": "Pengguna tidak wujud",
    "data": null
}

💎参数化

参数化为了对应可变提示,例如需要需要在错误提示中加入用户昵称来做错误提示,此时就需要参数化的错误提示

定义:

[ErrorType]
public enum Module1Error
{
    /// <summary>
    /// 参数
    /// </summary>
    [ErrorCodeItemMeta("触发错误:{0},原因:{1}", "error:{0},reason{1}")]
    WithParam = 10004
}

使用方式:

throw new ZException(Module1Error.WithParam, new string[] {"error", "user does not exist" });
//zh-Hans
{
    "code": 10004,
    "message": "触发错误:error,原因:user does not exist",
    "data": null
}

//en
{
    "code": 10004,
    "message": "error:error,reasonuser does not exist",
    "data": null
}

💎重写消息

同一个错误可能在不同场景业务需要返回不同的消息,重写消息就是为了对应这种情况;

使用方式:

throw new ZException(Module1Error.WithParam, "重写错误提示");
{
    "code": 10004,
    "message": "重写错误提示",
    "data": null
}

参数化:

throw new ZException(Module1Error.WithParam, "重写参数化:错误提示{0}-{1}", new string[] { "hello", "world" });
{
    "code": 10004,
    "message": "重写参数化:错误提示hello-world",
    "data": null
}

🍀更新

💎1.1.0

  • 增加消息参数化
  • 增加消息重写

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 109 10/25/2024
1.0.1 104 10/25/2024
1.0.0 147 10/18/2024