.NET Core combat development (Lesson 22: Exception processing middleware: logic to distinguish true anomaly and anomaly) - Study Notes (a)

22 is | exception processing middleware: logic to distinguish true anomaly and anomaly

In this section we explain to Error Handling Best Practices

Inside the exception handling system, ASP.NET Core provides four ways

1, exception handling page

2, exception handling anonymous delegate method

3、IExceptionFilter

4、ExceptionFilterAttribute

Source link:
https://github.com/witskeeper/geektime/tree/master/samples/ExceptionDemo

Startup of the Configure method

if (env.IsDevelopment())
{
    // 开发环境下的异常处理页
    app.UseDeveloperExceptionPage();
}

Controller to throw exceptions

throw new Exception("报个错");

Start the program, you see an error page

This error page prints More Information For more information and errors our current request, this page is not appropriate for the user to see, so this error page in a production environment is to be closed

Here's how normal processing error pages:

// 第一种方式就是定义错误页的方式
app.UseExceptionHandler("/error");

Define an interface IKnownException

namespace ExceptionDemo.Exceptions
{
    public interface IKnownException
    {
        public string Message { get; }

        public int ErrorCode { get; }

        public object[] ErrorData { get; }
    }
}

The default implementation KnownException

namespace ExceptionDemo.Exceptions
{
    public class KnownException : IKnownException
    {
        public string Message { get; private set; }

        public int ErrorCode { get; private set; }

        public object[] ErrorData { get; private set; }

        public readonly static IKnownException Unknown = new KnownException { Message = "未知错误", ErrorCode = 9999 };

        public static IKnownException FromKnownException(IKnownException exception)
        {
            return new KnownException { Message = exception.Message, ErrorCode = exception.ErrorCode, ErrorData = exception.ErrorData };
        }
    }
}

Why do we need to define such a type it?

Because exceptions are different systems inside our usually abnormal and our business logic, business logic above judgment exceptions, such as input parameters, the status of the order does not meet the conditions, the current account balance is insufficient, we have information like this two approaches:

A processing way is different on different business object logic output

Another way is for an abnormality such business logic, the output of an exception, special exception to carry diverging logic, this time need is identified which abnormal traffic, which is unknown abnormal uncertain, for example, network the exception request occurs, MySql a link disconnection, Redis connection abnormality has occurred

Then to carry the error message by defining an error page, such as our ErrorController, it is only one page, its role is to output an error message

namespace ExceptionDemo.Controllers
{
    [AllowAnonymous]
    public class ErrorController : Controller
    {
        [Route("/error")]
        public IActionResult Index()
        {
            // 获取当前上下文里面报出的异常信息
            var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            var ex = exceptionHandlerPathFeature?.Error;

            // 特殊处理,尝试转换为 IKnownException
            var knownException = ex as IKnownException;
            // 对于未知异常,我们并不应该把错误异常完整地输出给客户端,而是应该定义一个特殊的信息 Unknown 传递给用户
            // Unknown 其实也是一个 IKnownException 的实现,它的 Message = "未知错误", ErrorCode = 9999
            // 也就是说我们在控制器 throw new Exception("报个错"); 就会看到错误信息
            if (knownException == null)
            {
                var logger = HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
                // 我们看到的信息是未知错误,但是在我们的日志系统里面,我们还是记录的原有的异常信息
                logger.LogError(ex, ex.Message);
                knownException = KnownException.Unknown;
            }
            else// 当识别到异常是已知的业务异常时,输出已知的异常,包括异常消息,错误状态码和错误信息,就是在 IKnownException 中的定义
            {
                knownException = KnownException.FromKnownException(knownException);
            }
            return View(knownException);
        }
    }
}

View

@model ExceptionDemo.Exceptions.IKnownException
@{
    ViewData["Title"] = "Index";
}

<h1>错误信息</h1>

<div>Message:<label>@Model.Message</label></div>
<div>ErrorCode<label>@Model.ErrorCode</label></div>

After starting the program you can see the custom error page has been successfully rendered the

This is the first treatment wrong way

Creative Commons License

This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing.

Welcome to reprint, use, repost, but be sure to keep the article signed by Zheng Ziming (containing links: http://www.cnblogs.com/MingsonZheng/), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification .

If you have any questions, please contact me ([email protected]).

Guess you like

Origin www.cnblogs.com/MingsonZheng/p/12466561.html