public static void SetCustomExceptionHandler(this IApplicationBuilder application, bool isDevelopment) { application.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature.Error; var result = new ExceptionResponse { StatusCode = context.Response.StatusCode, Message = exception.Message }; if (isDevelopment) { result.StackTrace = exception.StackTrace; } context.Response.ContentType = "application/json"; await context.Response.WriteAsync(result.ToJson()); }); }); }
private async Task HandleExceptionAsync(HttpContext context, Exception exception) { var response = context.Response; var statusCode = (int)HttpStatusCode.InternalServerError; ExceptionResponse customException = new ExceptionResponse(); if (exception is DomainException) { customException.Message = customException.Message; statusCode = ((DomainException)exception).Code; } else { customException.Message = exception.Message; if (exception.InnerException != null) { customException.Message = exception.InnerException.Message; if (exception.InnerException?.InnerException != null) { customException.Message = exception.InnerException.InnerException.Message; } } } response.ContentType = "application/json"; response.StatusCode = statusCode; await response.WriteAsync(JsonConvert.SerializeObject(customException)); }
private void Dispose(Exception error) { ArrayList requests = null; lock (requestMap.SyncRoot) { if (this.error == null) { this.error = error; requests = new ArrayList(requestMap.Values); requestMap.Clear(); } } if (requests != null) { foreach (FutureResponse future in requests) { BrokerError brError = new BrokerError(); brError.Message = error.Message; ExceptionResponse response = new ExceptionResponse(); response.Exception = brError; future.Response = response; } } }
/// <summary> /// 处理异常信息 /// </summary> /// <param name="ex"></param> private ExceptionResponse FormatRpcException(Exception ex) { ExceptionResponse exceptionResponse; string message = GetRpcException(ex); if (!string.IsNullOrEmpty(message)) { if (message == "unauthorized") { exceptionResponse = new ExceptionResponse(HttpStatus.Unauthorized.Id, ErrCode.Unauthorized.Code, ex.Message); } else { var result = ServiceProvider.GetJsonProvider().Deserialize <BusinessResponse>(message); if (result == null) { exceptionResponse = new ExceptionResponse(HttpStatus.Err.Id, ErrCode.SystemError.Code, "系统繁忙,请稍后再试"); } else { exceptionResponse = new ExceptionResponse(HttpStatus.Err.Id, result.Code, result.Content); } } } else { exceptionResponse = new ExceptionResponse(HttpStatus.Err.Id, ErrCode.UnDisposed.Code, ErrCode.UnDisposed.Name); } return(exceptionResponse); }
public void Process(ISemanticProcessor proc, IMembrane membrane, ExceptionResponse resp) { // proc.ServiceManager.Get<ILoggerService>().Log(LogMessage.Create(resp.Exception.Message)); proc.ServiceManager.Get <ISemanticProcessor>().ProcessInstance <LoggerMembrane, ST_Exception>(ex => ex.Exception = resp.Exception); resp.Context.Response.ContentLength64 = resp.Exception.Message.Length; resp.Context.Response.Write(resp.Exception.Message, "text/text", 500); }
// // Write a object instance to data output stream // public override void LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut) { ExceptionResponse info = (ExceptionResponse)o; base.LooseMarshal(wireFormat, o, dataOut); LooseMarshalBrokerError(wireFormat, info.Exception, dataOut); }
public override void handleErrorOcurr() { ControllerEx ctrlEx = Core.EntityMgr.getControllerByID(SenderID); if (ctrlEx != null) { if (!string.IsNullOrEmpty(errorInfo)) { ctrlEx.Http_ErrorOccured(request, errorInfo); } else { if (response == null) { response = new ExceptionResponse(); } ExceptionResponse ex = response as ExceptionResponse; if (ex == null) { ex = new ExceptionResponse(); } ctrlEx.Http_ErrorOccured(request, ex.HttpError); } } else { ConsoleEx.DebugLog("Controller doesn't exist.", ConsoleEx.YELLOW); } }
private static void AppendStackTraceToStringBuilder(StringBuilder builder, ExceptionResponse ex) { if (!string.IsNullOrWhiteSpace(ex.StackTrace)) { foreach (var line in ex.StackTrace .Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None) .Select(s => s.Trim()) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => STACK_TRACE_INDENT + s)) { builder.AppendLine(line); } } if (ex.InnerException != null) { string errorMessage = ex.InnerException.ErrorMessage; string errorType = ex.InnerException.ErrorType; if (errorMessage != null) { builder.Append(errorMessage.Trim()); builder.Append(": "); } builder.AppendLine(errorType); AppendStackTraceToStringBuilder(builder, ex.InnerException); } }
private List <HardwareTemplate_Full> BAM_ApiPost(HardwareTemplate_Full newTemplate, HardwareTemplate_Full originalTemplate, List <HardwareTemplate_Full> returnValue, Models.HardwareTemplate_Json template) { var jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(template);//, jsonSettings var content = new StringContent(JsonConvert.SerializeObject(template), Encoding.UTF8, "application/json"); var queryResult_Set = _bamclient._client.PostAsync("api/V3/Projection/Commit", content).Result; if (!queryResult_Set.IsSuccessStatusCode) { string responseContent = queryResult_Set.Content.ReadAsStringAsync().Result; ExceptionResponse exceptionResponse = JsonConvert.DeserializeObject <ExceptionResponse>(responseContent); //throw new Exception(exceptionResponse.Exception); } var resultSring = queryResult_Set.Content.ReadAsStringAsync().Result; //var result = JsonConvert.DeserializeObject<List<BAM_HardwareTemplate>>(resultSring); /////-------------This could be moved out and converted into an async Task ---- we can handle response outside/// var result = JsonConvert.DeserializeObject <BAM_Api_SuccessResponse>(resultSring); //if (result.BaseId != newTemplate.BaseId) // throw new Exception("Updated BaseId's didn't match"); returnValue.Add(newTemplate); returnValue.Add(originalTemplate); return(returnValue); }
public void OnException(ExceptionContext context) { //var result = context.Result as ObjectResult; //if (result.StatusCode != StatusCodes.Status200OK) //{ context.ExceptionHandled = true; var resp = new ExceptionResponse(); var error = new Error() { Message = context.Exception.Message, Exception = context.Exception.Data.ToString(), StackTrace = context.Exception.StackTrace }; if (context.Exception.GetBaseException() is SqlException ex) { var num = ex.Number; if (num == 547) { error.Message = "Brisanje nije dozvoljeno"; } } resp.IsError = true; resp.Data = null; resp.Error = error; context.Result = new ObjectResult(resp); //} }
public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError($"[{context.TraceIdentifier}] Request failed with reason '{ex.Message}'"); var epcisException = ex as EpcisException ?? EpcisException.Default; context.Response.ContentType = context.Request.ContentType; context.Response.StatusCode = (int)(ex is EpcisException ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError); var requestContext = context.RequestServices.GetService <RequestContext>(); var response = new ExceptionResponse { Exception = epcisException.ExceptionType.DisplayName, Severity = epcisException.Severity, Reason = GetMessage(ex) }; await requestContext.Formatter.WriteResponse(response, context.Response.Body, context.RequestAborted); } }
public void OnResultExecuting(ResultExecutingContext context) { var result = context.Result as ObjectResult; if (result.StatusCode >= 200 && result.StatusCode <= 300) { var resp = new ExceptionResponse(); resp.Data = result.Value; resp.IsError = false; resp.Error = null; context.Result = new ObjectResult(resp); } else if (result.StatusCode >= 400 && result.StatusCode <= 500) { //result.StatusCode = (int) HttpStatusCode.InternalServerError; var resp = new ExceptionResponse(); resp.Data = "Internal Server Error"; resp.IsError = true; resp.Error = null; context.Result = new ObjectResult(resp) { StatusCode = StatusCodes.Status500InternalServerError }; } }
private void Dispose(Exception error) { ArrayList requests = null; lock (_requestMap.SyncRoot) if (_error == null) { _error = error; requests = new ArrayList(_requestMap.Values); _requestMap.Clear(); } if (requests == null) { return; } foreach (FutureResponse future in requests) { var brError = new BrokerError { Message = error?.Message }; var response = new ExceptionResponse { Exception = brError }; future.Response = response; } }
private async Task HandleExceptionAsync(HttpContext context, Exception ex) { var exception = ex; var status = exception is NotFoundException ? HttpStatusCode.NotFound : exception is ConflictException ? HttpStatusCode.Conflict : exception is UnauthorizedUserException ? HttpStatusCode.Unauthorized : exception is BusinessException ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError; var errorResponse = new ExceptionResponse(exception.Message, NotificationType.Error); var msg = exception.Message; if (ex is BusinessException == false && _env.IsDevelopment()) { errorResponse = new ExceptionResponse(msg, NotificationType.Error); } if (ex is UnauthorizedUserException) { errorResponse = new ExceptionResponse(ex.Message, NotificationType.Error); } if (ex is BusinessException businessException) { errorResponse.Title = businessException.Title; } await ProccessResponse(context, status, errorResponse); }
public void Save(int userId, [FromBody] List <Product> products) { try { if (products.Count == 0) { throw new RequestForbidden("Invalid Request"); } UserProfile _user = AuthManager.CurrentUser; if (_user == null || userId != _user.Id) { throw ExceptionResponse.Forbidden(Request, Messages.InvalidCredentials); } ProductServices.Save(userId, products); } catch (RequestForbidden ex) { throw ExceptionResponse.Forbidden(Request, ex.Message); } catch (Exception ex) { throw ExceptionResponse.ServerErrorResponse(Request); } }
private static void HandleCustomException(ExceptionContext filterContext) { var exception = filterContext.Exception; filterContext.ExceptionHandled = true; var response = filterContext.HttpContext.Response; response.ContentType = Constant.ApplicationJsonUtf8ContentType; if (filterContext.Exception is SolidamException) { response.StatusCode = (int)HttpStatusCode.InternalServerError; } var exceptionResponse = new ExceptionResponse(exception); if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = exceptionResponse }; } var jsonResponse = JsonConvert.SerializeObject(exceptionResponse, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); response.Write(jsonResponse); }
public async Task HandleAsync ( HttpContext context, Exception exception ) { ErrorResponse response; if (_hostingEnvironment.IsDevelopment()) { response = new ExceptionResponse ( new Models.Exception.Exception(exception) ); } else { response = new ErrorResponse(); } await context.Response.WriteJsonAsync ( HttpStatusCode.InternalServerError, response, JsonConstants.JsonSerializerSettings ); }
private static void AppendStackTraceToStringBuilder(StringBuilder builder, ExceptionResponse ex) { if (!string.IsNullOrWhiteSpace(ex.StackTrace)) { string[] array = (from s in ex.StackTrace.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None) select s.Trim() into s where !string.IsNullOrWhiteSpace(s) select STACK_TRACE_INDENT + s).ToArray(); foreach (string value in array) { builder.AppendLine(value); } } if (ex.InnerException != null) { string errorMessage = ex.InnerException.ErrorMessage; string errorType = ex.InnerException.ErrorType; if (errorMessage != null) { builder.Append(errorMessage.Trim()); builder.Append(": "); } builder.AppendLine(errorType); AppendStackTraceToStringBuilder(builder, ex.InnerException); } }
/// <summary> /// Method is invoked when middleware is switched. /// </summary> /// <param name="context">Context of the invocation.</param> /// <returns>Task of the invocation.</returns> public async Task InvokeAsync(HttpContext context) { try { if (this.requestDelegate != null) { // invoking next middleware. await this.requestDelegate.Invoke(context).ConfigureAwait(false); } } catch (Exception innerException) { this.logger.LogCritical(Constants.ErrorHandlingMiddlewareErrorCode, innerException, Constants.ErrorMiddlewareLog); ExceptionResponse currentException = new ExceptionResponse() { ErrorMessage = Constants.ErrorMiddlewareLog, CorrelationIdentifier = System.Diagnostics.Activity.Current?.RootId, }; if (this.includeExceptionDetailsInResponse) { currentException.InnerException = $"{innerException.Message} {innerException.StackTrace}"; } context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer.Serialize <ExceptionResponse>(currentException)).ConfigureAwait(false); } }
public override FutureResponse AsyncRequest(ICommand command) { var commandId = GetNextCommandId(); command.CommandId = commandId; command.ResponseRequired = true; var future = new FutureResponse(); Exception priorError; lock (_requestMap.SyncRoot) { priorError = _error; if (priorError == null) { _requestMap[commandId] = future; } } if (priorError != null) { var brError = new BrokerError { Message = priorError.Message }; var response = new ExceptionResponse { Exception = brError }; future.Response = response; throw priorError; } Next.Oneway(command); return(future); }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { var exceptionType = exception.GetType(); var statusCode = _statusCodes.ContainsKey(exceptionType) ? _statusCodes[exceptionType] : HttpStatusCode.InternalServerError; context.Response.ContentType = MediaTypeNames.Application.Json; context.Response.StatusCode = (int)statusCode; if (exception is IDiagnoseaException submarineException) { var response = new ExceptionResponse { ExceptionCode = submarineException.ExceptionCode, TechnicalMessage = submarineException.TechnicalMessage, UserMessage = submarineException.UserMessage }; var serialization = JsonConvert.SerializeObject(response, _jsonSerializerSettings); return(context.Response.WriteAsync(serialization)); } var fallbackResponse = new ExceptionResponse { ExceptionCode = (int)ExceptionCode.Unknown, TechnicalMessage = exception.Message }; var fallbackSerialization = JsonConvert.SerializeObject(fallbackResponse, _jsonSerializerSettings); return(context.Response.WriteAsync(fallbackSerialization)); }
public override FutureResponse AsyncRequest(ICommand command) { var commandId = GetNextCommandId(); command.CommandId = commandId; command.ResponseRequired = true; var future = new FutureResponse(); var priorError = _error; if (priorError == null) { _requestMap.AddOrUpdate(commandId, future, (k, v) => future); } if (priorError != null) { var brError = new BrokerError { Message = priorError.Message }; var response = new ExceptionResponse { Exception = brError }; future.Response = response; throw priorError; } Next.Oneway(command); return(future); }
protected virtual Object CreateCommand(string command, IDictionary headers, byte[] content) { if (command == "RECEIPT" || command == "CONNECTED") { string text = RemoveHeader(headers, "receipt-id"); if (text != null) { Response answer = new Response(); if (text.StartsWith("ignore:")) { text = text.Substring("ignore:".Length); } answer.CorrelationId = Int32.Parse(text); return(answer); } else if (command == "CONNECTED") { text = RemoveHeader(headers, "response-id"); if (text != null) { Response answer = new Response(); answer.CorrelationId = Int32.Parse(text); return(answer); } } } else if (command == "ERROR") { string text = RemoveHeader(headers, "receipt-id"); if (text != null && text.StartsWith("ignore:")) { Response answer = new Response(); answer.CorrelationId = Int32.Parse(text.Substring("ignore:".Length)); return(answer); } else { ExceptionResponse answer = new ExceptionResponse(); if (text != null) { answer.CorrelationId = Int32.Parse(text); } BrokerError error = new BrokerError(); error.Message = RemoveHeader(headers, "message"); error.ExceptionClass = RemoveHeader(headers, "exceptionClass"); // TODO is this the right header? answer.Exception = error; return(answer); } } else if (command == "MESSAGE") { return(ReadMessage(command, headers, content)); } Tracer.Error("Unknown command: " + command + " headers: " + headers); return(null); }
protected override void OnCommand(ITransport sender, Command command) { if (command.IsResponse) { Response response = (Response)command; int correlationId = response.CorrelationId; FutureResponse future = (FutureResponse)requestMap[correlationId]; if (future != null) { requestMap.Remove(correlationId); future.Response = response; if (response is ExceptionResponse) { ExceptionResponse er = response as ExceptionResponse; BrokerError brokerError = er.Exception; BrokerException exception = new BrokerException(brokerError); this.exceptionHandler(this, exception); } } else { if (Tracer.IsDebugEnabled) { Tracer.Debug("Unknown response ID: " + response.CommandId + " for response: " + response); } } } else { this.commandHandler(sender, command); } }
public ActionResult <ReconsultationResponse> Reconsultation([FromBody] ReConsultationRequest reConsultationRequest) { try { var reConsultationResponse = _userProcess.Reconsultation(reConsultationRequest); switch (reConsultationResponse.StatusCode) { case System.Net.HttpStatusCode.OK: return(Ok(reConsultationResponse)); case System.Net.HttpStatusCode.NotFound: return(NotFound(reConsultationResponse)); case System.Net.HttpStatusCode.BadRequest: return(BadRequest(reConsultationResponse)); case System.Net.HttpStatusCode.Conflict: return(Conflict(reConsultationResponse)); default: return(Ok()); } } catch (Exception exception) { var exceptionResponse = new ExceptionResponse { DeveloperMessage = exception.StackTrace, ExceptionMessage = exception.Message }; return(new ObjectResult(exceptionResponse) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }); } }
internal Response Excute(Request request) { var requestType = request.requestDescription; IExecutor executor = null; servicesLock.EnterReadLock(); try { methodMaps.TryGetValue(requestType, out executor); } finally { servicesLock.ExitReadLock(); } Response response; if (executor != null) { try { response = executor.Execute(request); response.Id = request.Id; } catch (Exception e) { executorLog.WriteLog("Exception when invoke type : " + executor.GetType().FullName + ", with exception: " + e); response = new ExceptionResponse(request.Id, e); } } else { response = new ExceptionResponse(request.Id, new ServiceNotFoundException(request.ToString())); } return(response); }
public override void OnException(ExceptionContext context) { if (context.HttpContext.Request.Body.CanSeek) { using (var requestSm = context.HttpContext.Request.Body) { var requestMethod = context.HttpContext.Request.Method; var requestHost = context.HttpContext.Request.Host.ToString(); var requestPath = context.HttpContext.Request.Path; var exception = context.Exception.Message; LogHelper.Error($"\r\nMethod:{requestMethod} \r\nHost:{requestHost} \r\nPath:{requestPath} \r\nException:{exception} \r\n"); } } var result = new ExceptionResponse { ErrCode = 500, ErrMsg = context.Exception.Message, BizErrorMsg = context.Exception.Message }; context.HttpContext.Response.StatusCode = 200; context.HttpContext.Response.ContentType = "application/json;charset=utf-8"; context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result)); base.OnException(context); }
public override FutureResponse AsyncRequest(Command command) { int commandId = GetNextCommandId(); command.CommandId = commandId; command.ResponseRequired = true; FutureResponse future = new FutureResponse(); Exception priorError = null; lock (requestMap.SyncRoot) { priorError = this.error; if (priorError == null) { requestMap[commandId] = future; } } if (priorError != null) { BrokerError brError = new BrokerError(); brError.Message = priorError.Message; ExceptionResponse response = new ExceptionResponse(); response.Exception = brError; future.Response = response; throw priorError; } next.Oneway(command); return(future); }
private void OnSCExceptionResponse(object responseMsg) { if (responseMsg is ExceptionRemoteLoginResponse) { ExceptionRemoteLoginResponse rsp = responseMsg as ExceptionRemoteLoginResponse; ConfMsgCode error_code = ConfMsgCode.Get(rsp.Status.Code); string error_str = "loading_FB_X"; if (null != error_code) { if (!string.IsNullOrEmpty(error_code.popStr) && !string.IsNullOrWhiteSpace(error_code.popStr)) { error_str = error_code.popStr; } } BackToLogin("Timeout", error_str); } else if (responseMsg is ExceptionResponse) { ExceptionResponse rsp = responseMsg as ExceptionResponse; ConfMsgCode error_code = ConfMsgCode.Get(rsp.Status.Code); string error_str = "server_unusual"; if (null != error_code) { if (!string.IsNullOrEmpty(error_code.popStr) && !string.IsNullOrWhiteSpace(error_code.popStr)) { error_str = error_code.popStr; } } BackToLogin("Timeout", error_str); } }
protected override void OnCommand(ITransport sender, Command command) { if (command is Response) { Response response = (Response)command; FutureResponse future = (FutureResponse)requestMap[response.CorrelationId]; if (future != null) { if (response is ExceptionResponse) { ExceptionResponse er = (ExceptionResponse)response; BrokerError brokerError = er.Exception; BrokerException exception = new BrokerException(brokerError); this.exceptionHandler(this, exception); } future.Response = response; } else { if (command is ShutdownInfo) { // lets shutdown this.commandHandler(sender, command); } else { Tracer.Error("Unknown response ID: " + response.CommandId + " for response: " + response); } } } else { this.commandHandler(sender, command); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, ExceptionResponse resp) { // proc.ServiceManager.Get<ILoggerService>().Log(LogMessage.Create(resp.Exception.Message)); proc.ServiceManager.Get<ISemanticProcessor>().ProcessInstance<LoggerMembrane, ST_Exception>(ex => ex.Exception = resp.Exception); resp.Context.Response.StatusCode = 500; resp.Context.Response.ContentType = "text/text"; resp.Context.Response.ContentEncoding = Encoding.UTF8; resp.Context.Response.ContentLength64 = resp.Exception.Message.Length; resp.Context.Response.OutputStream.Write(resp.Exception.Message.to_Utf8(), 0, resp.Exception.Message.Length); resp.Context.Response.Close(); }
public void OnException(ExceptionContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.IsChildAction) { return; } // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { // return; } Exception exception = filterContext.Exception; Log.Error(exception); // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (new HttpException(null, exception).GetHttpCode() != 500) { // return; } filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = (int)this.StatusCode; filterContext.HttpContext.Response.ContentType = "application/xml"; var response = new ExceptionResponse(exception); response.WriteToStream(filterContext.HttpContext.Response.OutputStream); // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }