public async Task Invoke(DownstreamContext context) { var response = await _requester.GetResponse(context); if (response.IsError) { Logger.LogDebug("IHttpRequester returned an error, setting pipeline error"); SetPipelineError(context, response.Errors); return; } else if (response.Data.StatusCode != System.Net.HttpStatusCode.OK) { //如果后端未处理异常,设置异常信息,统一输出,防止暴露敏感信息 if (response.Data.StatusCode == System.Net.HttpStatusCode.BadRequest) { //提取Ids4相关的异常(400) var result = await response.Data.Content.ReadAsStringAsync(); JObject jobj = JObject.Parse(result); var errorMsg = jobj["error"]?.ToString(); var error = new IdentityServer4Error(errorMsg ?? "未知异常"); SetPipelineError(context, error); return; } else { var error = new InternalServerError($"请求服务异常"); Logger.LogWarning($"路由地址 {context.HttpContext.Request.Path} 请求服务异常. {error}"); SetPipelineError(context, error); return; } } Logger.LogDebug("setting http response message"); context.DownstreamResponse = new DownstreamResponse(response.Data); }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { var code = HttpStatusCode.InternalServerError; var response = new InternalServerError { HttpStatusCode = (int)code, UserMessage = "Internal Server Error", MoreInfo = "An unexpected error has occured.", DeveloperMessage = "Detailed information about the error has been logged.", Errors = new List <ErrorResponse> (), IsError = true, RequestId = context.TraceIdentifier }; var result = JsonSerializer.Serialize(response); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); // context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; // logger = new Logger { // StracTrace = exception.StackTrace, // ClassName = exception.Source, // Message = exception.Message, // StatusCode = context.Response.StatusCode // }; // _errorLogger.LogError (); // logger.ErrorLog (exception); // return context.Response.WriteAsync (logger.ToString ()); }
public async Task Invoke(DownstreamContext context) { var httpStatusCode = HttpStatusCode.OK; var _param = new List <object>(); //1、提取路由参数 var tmpInfo = context.TemplatePlaceholderNameAndValues; if (tmpInfo != null && tmpInfo.Count > 0) { foreach (var tmp in tmpInfo) { _param.Add(tmp.Value); } } //2、提取query参数 foreach (var _q in context.HttpContext.Request.Query) { _param.Add(_q.Value.ToString()); } //3、从body里提取内容 if (context.HttpContext.Request.Method.ToUpper() != "GET") { context.DownstreamRequest.Scheme = "http"; var requert = context.DownstreamRequest.ToHttpRequestMessage(); if (requert.Content != null) { var json = "{}"; json = await requert.Content.ReadAsStringAsync(); _param.Add(json); } } //从缓存里提取 var req = await _czarRpcProcessor.GetRemoteMethodAsync(context.DownstreamReRoute.UpstreamPathTemplate.OriginalValue); if (req != null) { req.Parameters = _param.ToArray(); var result = await _clientFactory.SendAsync(req, GetEndPoint(context.DownstreamRequest.Host, context.DownstreamRequest.Port)); OkResponse <RpcHttpContent> httpResponse; if (result.CzarCode == Czar.Rpc.Utilitys.RpcStatusCode.Success) { httpResponse = new OkResponse <RpcHttpContent>(new RpcHttpContent(result.CzarResult?.ToString())); } else { httpResponse = new OkResponse <RpcHttpContent>(new RpcHttpContent(result)); } context.HttpContext.Response.ContentType = "application/json"; context.DownstreamResponse = new DownstreamResponse(httpResponse.Data, httpStatusCode, httpResponse.Data.Headers, "OK"); } else {//输出错误 var error = new InternalServerError($"请求路由 {context.HttpContext.Request.Path}未配置后端转发"); Logger.LogWarning($"{error}"); SetPipelineError(context, error); } }
public void MakeInternalServerError_NullExIncludeDetails_GenericErrorReturned() { InternalServerError error = Errors.MakeInternalServerError(exception: null, includeDetails: true); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.IsNotEmpty(error.unique_id); Assert.IsNotEmpty(error.message); Assert.IsEmpty(error.server_stack_trace); Assert.IsEmpty(error.inner_errors); }
public void SetUp() { var mediaType = new Mock<IMediaType>(); mediaType.SetupGet(mt => mt.Synonyms).Returns(new[] { "media-type" }); result = new InternalServerError { MediaType = mediaType.Object }; }
public void MakeInternalServerError_ExIncludeDetails_HasStackAndInnerExceptions() { var ex = GenerateException(new Exception("this is some message", GenerateException <InvalidOperationException>())); InternalServerError error = Errors.MakeInternalServerError(ex, includeDetails: true); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.IsNotEmpty(error.unique_id); Assert.That(error.message, Is.StringContaining(ex.Message)); Assert.IsNotEmpty(error.server_stack_trace); Assert.AreEqual(1, error.inner_errors.Count); }
/// <summary> /// Creates an <see cref="InternalServerError"/> with the given message. /// </summary> /// <param name="message">An error message.</param> /// <param name="uniqueId">The ID of the request that caused this error. This should not be null, /// but if it is, the generated error will contain an empty string.</param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(string message, string uniqueId) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.INTERNAL_SERVER_ERROR, unique_id = uniqueId ?? string.Empty, message = message ?? InternalErrorMessage }; return(internalServerError); }
public void MakeInternalServerError_DontIncludeDetails_GenericErrorReturned() { var ex = new InvalidOperationException("You can't do that."); InternalServerError error = Errors.MakeInternalServerError(ex, includeDetails: false); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.IsNotEmpty(error.unique_id); Assert.That(error.message, Is.Not.StringContaining(ex.Message)); Assert.IsEmpty(error.server_stack_trace); Assert.IsEmpty(error.inner_errors); }
/// <summary> /// Creates an <see cref="InternalServerError"/> with the given message. /// </summary> /// <param name="message">An error message.</param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(string message) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = Guid.NewGuid().ToString("D") }; internalServerError.message = message ?? InternalErrorMessage; return internalServerError; }
/// <summary> /// Creates an <see cref="InternalServerError"/> with the given message. /// </summary> /// <param name="message">An error message.</param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(string message) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = Guid.NewGuid().ToString("D") }; internalServerError.message = message ?? InternalErrorMessage; return(internalServerError); }
/// <summary> /// Creates an <see cref="InternalServerError"/> with the given message. /// </summary> /// <param name="message">An error message.</param> /// <param name="uniqueId">The ID of the request that caused this error. This should not be null, /// but if it is, the generated error will contain an empty string.</param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(string message, string uniqueId) { var internalServerError = new InternalServerError { error_code = (int) ErrorCode.INTERNAL_SERVER_ERROR, unique_id = uniqueId ?? string.Empty, message = message ?? InternalErrorMessage }; return internalServerError; }
/// <summary> /// Creates an <see cref="InternalServerError"/> with the given message. /// </summary> /// <param name="message">An error message.</param> /// <param name="uniqueId">The ID of the request that caused this error. This should not be null, /// but if it is, the generated error will contain an empty string.</param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(string message, string uniqueId) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = uniqueId ?? "", message = message ?? InternalErrorMessage }; return(internalServerError); }
public void MakeInternalServerError_AggExIncludeDetails_HasStackAndInnerExceptions() { var innerExceptions = new[] { GenerateException <ArgumentException>(), GenerateException <InvalidOperationException>() }; var aggEx = GenerateException(new AggregateException("this is some message", innerExceptions)); InternalServerError error = Errors.MakeInternalServerError(aggEx, includeDetails: true); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.IsNotEmpty(error.unique_id); Assert.That(error.message, Is.StringContaining(aggEx.Message)); Assert.IsNotEmpty(error.server_stack_trace); Assert.AreEqual(2, error.inner_errors.Count); }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { // Response Error errorResponse; switch (exception) { case UnauthorizedException _: // 401 var unauthorizedException = (UnauthorizedException)exception; errorResponse = new Unauthorized(nameof(ErrorMessage.Unauthorized), unauthorizedException.Message); break; case ForbiddenException _: // 403 var forbiddenException = (ForbiddenException)exception; errorResponse = new Forbidden(nameof(ErrorMessage.Forbidden), forbiddenException.Message); break; case NotFoundException _: // 404 var notFoundException = (NotFoundException)exception; errorResponse = new NotFound(nameof(ErrorMessage.NotFound), notFoundException.Message); break; case ConflictException _: // 409 var conflictException = (ConflictException)exception; errorResponse = new Conflict(nameof(ErrorMessage.Conflict), conflictException.Message); break; default: // 500 errorResponse = new InternalServerError(nameof(ErrorMessage.InternalServerError), ErrorMessage.InternalServerError); // Log error _logger.LogSplunkError(exception); break; } var response = JsonConvert.SerializeObject(errorResponse, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List <JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter() } }); context.Response.ContentType = "application/json"; context.Response.StatusCode = errorResponse.Status; return(context.Response.WriteAsync(response)); }
public void MakeInternalServerError_AggExIncludeDetails_HasStackAndInnerExceptions() { var innerExceptions = new[] { GenerateException <ArgumentException>(), GenerateException <InvalidOperationException>() }; var aggEx = GenerateException(new AggregateException("this is some message", innerExceptions)); InternalServerError error = Errors.MakeInternalServerError(aggEx, "some ID", includeDetails: true); Assert.AreEqual((int)ErrorCode.INTERNAL_SERVER_ERROR, error.error_code); Assert.IsNotEmpty(error.unique_id); Assert.That(error.message, Is.StringContaining(aggEx.Message)); Assert.IsNotEmpty(error.server_stack_trace); Assert.IsNotNull(error.inner_error); var aggError = error.inner_error.Deserialize <AggregateError>(); Assert.AreEqual((int)ErrorCode.MULTIPLE_ERRORS_OCCURRED, aggError.error_code); Assert.That(aggError.message, Is.StringMatching("One or more errors occured")); Assert.AreEqual(2, aggError.inner_errors.Count); }
/// <summary> /// Creates an <see cref="InternalServerError"/> from an exception. /// </summary> /// <param name="exception">An exception.</param> /// <param name="uniqueId">The ID of the request that caused this error. This should not be null, /// but if it is, the generated error will contain an empty string.</param> /// <param name="includeDetails"> /// <c>true</c> if debugging details should be included; <c>false</c> /// to omit this potentailly sensitive information /// </param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(Exception exception, string uniqueId, bool includeDetails) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.INTERNAL_SERVER_ERROR, unique_id = uniqueId ?? string.Empty }; if (includeDetails && exception != null) { internalServerError.message = InternalErrorMessage + ": " + exception.Message; internalServerError.server_stack_trace = exception.StackTrace; var aggEx = exception as AggregateException; if (aggEx != null) { var aggregateError = new AggregateError { error_code = (int) ErrorCode.MULTIPLE_ERRORS_OCCURRED, message = "One or more errors occured", inner_errors = new List<IBonded<Error>>(aggEx.InnerExceptions.Count) }; foreach (var innerException in aggEx.InnerExceptions) { var innerError = MakeInternalServerError(innerException, uniqueId, includeDetails); aggregateError.inner_errors.Add(new Bonded<InternalServerError>(innerError)); } internalServerError.inner_error = new Bonded<AggregateError>(aggregateError); } else if (exception.InnerException != null) { var innerError = MakeInternalServerError(exception.InnerException, uniqueId, includeDetails); internalServerError.inner_error = new Bonded<InternalServerError>(innerError); } } else { internalServerError.message = InternalErrorMessage; } return internalServerError; }
/// <summary> /// Creates an <see cref="InternalServerError"/> from an exception. /// </summary> /// <param name="exception">An exception.</param> /// <param name="uniqueId">The ID of the request that caused this error. This should not be null, /// but if it is, the generated error will contain an empty string.</param> /// <param name="includeDetails"> /// <c>true</c> if debugging details should be included; <c>false</c> /// to omit this potentailly sensitive information /// </param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(Exception exception, string uniqueId, bool includeDetails) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = uniqueId ?? "" }; if (includeDetails && exception != null) { internalServerError.message = InternalErrorMessage + ": " + exception.Message; internalServerError.server_stack_trace = exception.StackTrace; var aggEx = exception as AggregateException; if (aggEx != null) { var aggregateError = new AggregateError { error_code = (int)ErrorCode.MultipleErrorsOccured, message = "One or more errors occured", inner_errors = new List <IBonded <Error> >(aggEx.InnerExceptions.Count) }; foreach (var innerException in aggEx.InnerExceptions) { var innerError = MakeInternalServerError(innerException, uniqueId, includeDetails); aggregateError.inner_errors.Add(new Bonded <InternalServerError>(innerError)); } internalServerError.inner_error = new Bonded <AggregateError>(aggregateError); } else if (exception.InnerException != null) { var innerError = MakeInternalServerError(exception.InnerException, uniqueId, includeDetails); internalServerError.inner_error = new Bonded <InternalServerError>(innerError); } } else { internalServerError.message = InternalErrorMessage; } return(internalServerError); }
public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { var statusCode = GetHttpStatusCodeFromExceptionType(ex); object result; if (ex is CoreException) { logger.LogInformation(ex, ex.Message); result = new BadRequestError(ex as CoreException); } else { var internalServerError = new InternalServerError(ex); if (ex is AggregateException) { foreach (var inner in (ex as AggregateException).InnerExceptions) { logger.LogError(inner, $"An aggregate internal error occurred [LogId:{internalServerError.LogId}].", internalServerError.LogId); } } else { logger.LogError(ex, $"An internal error occurred [LogId:{internalServerError.LogId}].", internalServerError.LogId); } result = internalServerError; } context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)statusCode; await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new GeneralJsonSerializerSettings())); } }
public void CleanseInternalServerError_WithInternalServerError() { InternalServerError originalInternalError = Errors.MakeInternalServerError(GenerateException <InvalidOperationException>(), includeDetails: true); string savedID = originalInternalError.unique_id; Error cleansedError = Errors.CleanseInternalServerError(originalInternalError); Assert.NotNull(cleansedError); InternalServerError cleansedInternalError = cleansedError as InternalServerError; Assert.NotNull(cleansedInternalError); Assert.AreEqual((int)ErrorCode.InternalServerError, cleansedInternalError.error_code); Assert.AreEqual(Errors.InternalErrorMessage, cleansedInternalError.message); Assert.IsEmpty(cleansedInternalError.inner_errors); Assert.AreEqual(savedID, cleansedInternalError.unique_id); Assert.IsEmpty(cleansedInternalError.server_stack_trace); }
/// <summary> /// Creates an <see cref="InternalServerError"/> from an exception. /// </summary> /// <param name="exception">An exception.</param> /// <param name="includeDetails"> /// <c>true</c> if debugging details should be included; <c>false</c> /// to omit this potentailly sensitive information /// </param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(Exception exception, bool includeDetails) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = Guid.NewGuid().ToString("D") }; if (includeDetails && exception != null) { internalServerError.message = InternalErrorMessage + ": " + exception.Message; internalServerError.server_stack_trace = exception.StackTrace; var aggEx = exception as AggregateException; if (aggEx != null) { internalServerError.inner_errors = new List<IBonded<Error>>(aggEx.InnerExceptions.Count); foreach (var innerException in aggEx.InnerExceptions) { var innerError = MakeInternalServerError(innerException, includeDetails); internalServerError.inner_errors.Add(new Bonded<InternalServerError>(innerError)); } } else if (exception.InnerException != null) { internalServerError.inner_errors = new List<IBonded<Error>>(1); var innerError = MakeInternalServerError(exception.InnerException, includeDetails); internalServerError.inner_errors.Add(new Bonded<InternalServerError>(innerError)); } } else { internalServerError.message = InternalErrorMessage; } return internalServerError; }
/// <summary> /// Creates an <see cref="InternalServerError"/> from an exception. /// </summary> /// <param name="exception">An exception.</param> /// <param name="includeDetails"> /// <c>true</c> if debugging details should be included; <c>false</c> /// to omit this potentailly sensitive information /// </param> /// <returns>An InternalServerError representing the exception.</returns> public static InternalServerError MakeInternalServerError(Exception exception, bool includeDetails) { var internalServerError = new InternalServerError { error_code = (int)ErrorCode.InternalServerError, unique_id = Guid.NewGuid().ToString("D") }; if (includeDetails && exception != null) { internalServerError.message = InternalErrorMessage + ": " + exception.Message; internalServerError.server_stack_trace = exception.StackTrace; var aggEx = exception as AggregateException; if (aggEx != null) { internalServerError.inner_errors = new List <IBonded <Error> >(aggEx.InnerExceptions.Count); foreach (var innerException in aggEx.InnerExceptions) { var innerError = MakeInternalServerError(innerException, includeDetails); internalServerError.inner_errors.Add(new Bonded <InternalServerError>(innerError)); } } else if (exception.InnerException != null) { internalServerError.inner_errors = new List <IBonded <Error> >(1); var innerError = MakeInternalServerError(exception.InnerException, includeDetails); internalServerError.inner_errors.Add(new Bonded <InternalServerError>(innerError)); } } else { internalServerError.message = InternalErrorMessage; } return(internalServerError); }
public async Task MethodCall_WithServiceError() { await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message <PairedInput>(input); IMessage <Output> multiplyResponse = await calculatorProxy.MultiplyAsync(request, System.Threading.CancellationToken.None); Assert.IsTrue(multiplyResponse.IsError); InternalServerError error = multiplyResponse.Error.Deserialize <InternalServerError>(); Assert.AreEqual((int)ErrorCode.INTERNAL_SERVER_ERROR, error.error_code); Assert.That(error.message, Is.StringContaining(Errors.InternalErrorMessage)); }
public ExceptionFromServicesException(HttpStatusCode httpStatusCode, InternalServerError internalServerError) : this(httpStatusCode) { InternalServerError = internalServerError; }
public void Apply(OpenApiOperation operation, OperationFilterContext context) { var apiDescription = context.ApiDescription; operation.Deprecated |= apiDescription.IsDeprecated(); if (operation.Parameters == null) { return; } foreach (var response in operation.Responses) { BaseException baseException; switch (response.Key) { case "400": baseException = new BadRequestException(); break; case "401": baseException = new UnauthorizedException(); break; case "403": baseException = new UnauthorizedException(); break; case "404": baseException = new NotFoundException(); break; case "406": baseException = new NotAcceptableException(); break; case "422": baseException = new UnprocessableException(); break; case "500": baseException = new InternalServerError(); break; default: baseException = null; break; } if (baseException != null) { response.Value.Description = baseException.ProblemDetailsModel.Detail; } } foreach (var parameter in operation.Parameters) { var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); if (String.IsNullOrEmpty(parameter.Description) && !String.IsNullOrEmpty(description?.ModelMetadata?.Description)) { parameter.Description = description.ModelMetadata?.Description; } if (parameter.Schema.Default == null && description.DefaultValue != null) { parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString()); } parameter.Required |= description.IsRequired; } }
public override void OnException(ExceptionContext context) { ExceptionSaver.SaveUnhandledException(ExceptionLogFolder, context.Exception, nameof(Dvin), e => { }); context.Result = new JsonResult(InternalServerError.Create("An exception was logged. We are sorry for the inconvenience.")); }
return new HttpError(InternalServerError, "Internal Server Error");
public WebResponseHandler(string scriptPath, ref WebRequestHandler request) { #region Generating objects for this request requestData = new JsonObject(); m_template = Template.GetRawTemplate(); #endregion #region Checking request parameters. // // Just checking some request parameters. This HTTP server // doesn't support a lot of things, so we need to send // error responses for the things it doesn't support. // if (request.path == null || request.path.Length <= 0) { m_template = Templates.Default.BadRequest.GetTemplate( ref request, ref requestData); return; } if (request.connectingHost == null || request.connectingHost.Length <= 0) { m_template = Templates.Default.BadRequest.GetTemplate( ref request, ref requestData); return; } if (request.mode != "GET" && request.mode != "POST") { m_template = Templates.Default.BadRequest.GetTemplate( ref request, ref requestData); m_template.AppendContent("Unsupported request method"); return; } if (request.protocolVersion != "HTTP/1.1" && request.protocolVersion != "HTTP/1.0") { m_template = Templates.Default.HTTPVersionNotSupported.GetTemplate( ref request, ref requestData); return; } #endregion try { #region Prepend m_template = Template.MergeTemplates( m_template, Templates.Custom.Special.Prepend.GetTemplate( ref request, ref requestData)); #endregion switch (scriptPath) { #region Action case "/action": { if (request.mode == "POST") { m_template = Template.MergeTemplates( m_template, Templates.Custom.TemplateAction.GetTemplate( ref request, ref requestData)); } else { // Method must be POST. Send an error page. m_template.SetHeader("Content-Type", "text/plain"); m_template.AppendContent("Content must be uploaded using the HTTP method POST."); m_template.SetStatus(500, "Internal Server Error"); } break; } #endregion #region Login case "/login": { m_template = Template.MergeTemplates( m_template, Templates.Custom.TemplateLogin.GetTemplate( ref request, ref requestData)); break; } #endregion #region Register case "/register": { m_template = Template.MergeTemplates( m_template, Templates.Custom.TemplateRegister.GetTemplate( ref request, ref requestData)); break; } #endregion #region 404 default: { m_template = Template.MergeTemplates( m_template, NotFound.GetTemplate( ref request, ref requestData)); break; } #endregion } #region Append m_template = Template.MergeTemplates( m_template, Templates.Custom.Special.Append.GetTemplate( ref request, ref requestData)); #endregion } catch (Exception ex) { Logs.LogException(ex.ToString()); // Don't merge templates for stuff like this m_template = InternalServerError.GetTemplate( ref request, ref requestData); } }