异常处理
大约 2 分钟
异常处理
通常一个 web 开发中,有大量需要处理的异常。比如业务异常,权限不足,数据库异常等等。前端通过弹出提示信息的方式告诉用户出了什么错误。通常情况下我们用 try ...... catch...
对异常进行捕获,但是在实际项目中业务模块进行异常捕获,会造成代码的冗余,不够优雅,我们希望代码中只有业务相关的操作,所有的异常通过一个类 GlobalExceptionMiddleware
中间件的形式进行集中处理。全局异常就是对框架所有异常进行统一管理。这样我们的代码就很简洁了。
如何使用
/// <summary>
/// 登录验证
/// </summary>
/// <param name="loginBody"></param>
/// <returns></returns>
public SysUser Login(LoginBodyDto loginBody)
{
SysUser user = SysLogininfoRepository.Login(loginBody);
if (user == null)
{
throw new CustomException(ResultCode.LOGIN_ERROR ,"用户名或密码错误");
}
return user;
}
当我们登录输入错误的用户名或密码时将返回以下结果
{
"msg": "用户名或密码错误",
"code": 105
}
CustomException 重载方法
public CustomException(string msg) : base(msg)
{
}
public CustomException(int code, string msg) : base(msg)
{
Code = code;
Msg = msg;
}
public CustomException(ResultCode resultCode, string msg) : base(msg)
{
Code = (int)resultCode;
}
/// <summary>
/// 自定义异常
/// </summary>
/// <param name="resultCode"></param>
/// <param name="msg"></param>
/// <param name="errorMsg">用于记录详细日志到输出介质</param>
public CustomException(ResultCode resultCode, string msg, object errorMsg) : base(msg)
{
Code = (int)resultCode;
LogMsg = errorMsg.ToString();
}
更多用法
throw new CustomException("使用默认code");
throw new CustomException(100, "自定义code");
throw new CustomException(ResultCode.LOGIN_ERROR ,"固定code值");
throw new CustomException(ResultCode.FAIL, "出错了", "记录日志使用,打印出更详细的日志内容");
ResultCode 自带 code 值
public enum ResultCode
{
[Description("success")]
SUCCESS = 200,
[Description("没有更多数据")]
NO_DATA = 210,
[Description("参数错误")]
PARAM_ERROR = 101,
[Description("验证码错误")]
CAPTCHA_ERROR = 103,
[Description("登录错误")]
LOGIN_ERROR = 105,
[Description("操作失败")]
FAIL = 1,
[Description("服务端出错啦")]
GLOBAL_ERROR = 500,
[Description("自定义异常")]
CUSTOM_ERROR = 110,
[Description("非法请求")]
INVALID_REQUEST = 116,
[Description("授权失败")]
OAUTH_FAIL = 201,
[Description("未授权")]
DENY = 401,
[Description("授权访问失败")]
FORBIDDEN = 403,
[Description("Bad Request")]
BAD_REQUEST = 400
}