Пример #1
0
        public async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var isAjaxRequest = context.Request.IsAjaxRequest();
            var isAcceptJson  = context.Request.Headers["Accept"]
                                .ToString()?
                                .Contains("application/json", StringComparison.OrdinalIgnoreCase) ?? false;

            var res = new ExceptionResult();

            switch (exception)
            {
            case AlertException alertException:
                res.Code    = alertException.ErrorCode;
                res.Message = alertException.Message;
                break;

            case FatalException fatalException:
                res.Code    = fatalException.ErrorCode;
                res.Message = fatalException.Message;
                _logger.LogError("致命错误", exception);
                break;

            case MozAspectInvocationException aspectInvocationException:
                res.Code    = aspectInvocationException.ErrorCode;
                res.Message = aspectInvocationException.ErrorMessage;
                break;

            case MozException mozException:
                res.Code    = mozException.ErrorCode;
                res.Message = mozException.Message;
                break;

            default:
                res.Code    = 20000;
                res.Message = exception.Message;
                _logger.LogError("系统错误", exception);
                break;
            }

            if (isAjaxRequest || isAcceptJson)
            {
                await this.OnApiCallAsync(context, res);
            }
            else
            {
                if (_webHostEnvironment.IsDevelopment())
                {
                    throw exception;
                }
                await OnPageCallAsync(context, res);
            }
        }
Пример #2
0
 protected virtual async Task OnPageCallAsync(HttpContext context, ExceptionResult result)
 {
     context.Response.ContentType = "text/html;charset=utf-8";
     context.Response.StatusCode  = 200;
     await context.Response.WriteAsync($"错误:{result.Message}({result.Code})");
 }
Пример #3
0
 protected virtual async Task OnApiCallAsync(HttpContext context, ExceptionResult result)
 {
     context.Response.ContentType = "application/json;charset=utf-8";
     context.Response.StatusCode  = 200;
     await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
 }