public async Task Invoke(HttpContext context) { ReturnResult errorInfo = null; try { await _next(context); } catch (FengException ex) { var newMsg = _errorCodeStore.StringGet(ex.ErrorCode); if (string.IsNullOrWhiteSpace(newMsg)) { newMsg = ex.ErrorMessage; } errorInfo = new ReturnResult(newMsg); } catch (Exception ex) { errorInfo = new ReturnResult("系统开小差了,请稍后再试"); _logger.LogError(ex, $"全局异常捕获,状态码:{ context?.Response?.StatusCode},Url:{context?.Request?.GetDisplayUrl()}"); } finally { if (errorInfo != null) { var Message = JsonConvert.SerializeObject(errorInfo); await HandleExceptionAsync(context, Message); } } }
public async Task Invoke(HttpContext context) { try { await _next(context); } catch (BucketException ex) { var newMsg = _errorCodeStore.StringGet(ex.ErrorCode); if (string.IsNullOrWhiteSpace(newMsg)) { newMsg = ex.ErrorMessage; } if (string.IsNullOrWhiteSpace(newMsg)) { newMsg = "未知异常,请稍后再试"; } context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync("{\"ErrorCode\": \"" + ex.ErrorCode + "\", \"Message\": \"" + newMsg + "\"}"); } catch (Exception ex) { _logger.LogError(ex, $"全局异常捕获,状态码:{ context?.Response?.StatusCode},Url:{context?.Request?.GetDisplayUrl()}"); // 开启异常,方便外层组件熔断等功能使用 context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "text/plain;charset=utf-8"; await context.Response.WriteAsync("error occurred"); } }