//异常错误信息捕获,将错误信息用Json方式返回 private static Task HandleExceptionAsync(Microsoft.AspNetCore.Http.HttpContext context, Exception ex, int statusCode) { StringBuilder builder = new StringBuilder(ex.Message); ErrorHandlingMiddleware.GetExceptionMessage(ex, builder); ApiResult apiResult = new ApiResult() { Success = false, Data = new ApiResultData() { Message = builder.ToString(), RequestUrl = context.Request.Path, ExceptionCode = statusCode } }; if (ex is BusinessException) { apiResult.Data.ExceptionCode = (ex as BusinessException).ExceptionCode; } var result = JsonConvert.SerializeObject(apiResult); context.Response.ContentType = "application/json;charset=utf-8"; GlobalConstants.DefaultLogger.Error(result); GlobalConstants.DefaultLogger.Error(ex.StackTrace); return(context.Response.WriteAsync(result)); }
private static void GetExceptionMessage(Exception ex, StringBuilder builder) { if (ex.InnerException != null) { builder.Append("\r\n"); builder.Append(ex.InnerException.Message); Exception innerException = ex.InnerException; ErrorHandlingMiddleware.GetExceptionMessage(innerException, builder); } }