private static ExceptionInfo CreatExceptionInfo(ExceptionDto dto) { return(dto == null ? null : ExceptionInfo.Create(dto.Message, dto.Source, dto.StackTrace, CreatExceptionInfo(dto.InnerException))); }
public override Response toResponse(RestException exception) { Response.Status responseStatus = ExceptionHandlerHelper.Instance.getStatus(exception); ExceptionDto exceptionDto = ExceptionHandlerHelper.Instance.fromException(exception); LOGGER.log(Level.WARNING, getStackTrace(exception)); return(Response.status(responseStatus).entity(exceptionDto).type(MediaType.APPLICATION_JSON_TYPE).build()); }
public WardenCheckResultDto(WardenCheckResult result) { IsValid = result.IsValid; WatcherCheckResult = new WatcherCheckResultDto(result.WatcherCheckResult); StartedAt = result.StartedAt; CompletedAt = result.CompletedAt; ExecutionTime = result.ExecutionTime; Exception = result.Exception == null ? null : new ExceptionDto(result.Exception); }
private void Log(Exception e) { var dto = new ExceptionDto { ExceptionMessage = e.Message, InnerExceptionMessage = e.InnerException?.Message, StackTrace = e.StackTrace }; this._exceptionRepository.Save(dto); }
public static Exception ToEntity(this ExceptionDto dto) { return(new Exception { ID = dto.ID, Message = dto.Message, InnerException = dto.InnerException, StackTrace = dto.StackTrace, Timestamp = dto.Timestamp }); }
/// <summary> /// /// </summary> /// <param name="context"></param> public override Task OnExceptionAsync(ExceptionContext context) { var code = HttpStatusCode.InternalServerError; IEnumerable <string>?errors = null; if (context.Exception is ValidationException validationException) { code = HttpStatusCode.BadRequest; errors = validationException.Errors.Select(validationFailure => validationFailure.ErrorMessage); } if (context.Exception is NotFoundException) { code = HttpStatusCode.NotFound; } context.HttpContext.Response.ContentType = MimeTypeConstants.Json; context.HttpContext.Response.StatusCode = (int)code; var exceptionBaseModel = new ExceptionDto( exceptionMessage: context.Exception.Message, exceptionStackTrace: context.Exception.StackTrace, innerExceptionMessage: context.Exception.InnerException?.Message, innerExceptionStackTrace: context.Exception.InnerException?.StackTrace, errors: errors ); var exceptionModel = _webApiConfiguration.AppConfiguration.AppEnvironment switch { AppEnvironment.Production => new ExceptionDto( exceptionMessage: MessageConstants.UnhandledExceptionMessage, innerExceptionMessage: null, exceptionStackTrace: null, innerExceptionStackTrace: null, errors: errors ), _ => exceptionBaseModel, }; context.Result = new JsonResult( value: exceptionModel ); _logger.LogWarning( exception: context.Exception, message: "Unhandled exception with message {0} was caught.", args: new object[] { context.Exception.Message } ); return(Task.CompletedTask); }
public static ApiExceptionDto CreateApiErrorException(int httpStatusCode, string message) { var exceptionDto = new ExceptionDto { Message = message }; var apiErrorException = new ApiExceptionDto { HttpStatusCode = httpStatusCode, Exception = exceptionDto }; return(apiErrorException); }
public ServiceResponse <bool> Save(ExceptionDto exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } var ex = exception.ToEntity(); _unitOfWork.Get <CORE.Exception>().Add(ex); _unitOfWork.Save(); return(new SuccessResponse <bool>(true)); }
private static Task HandleExceptionAsync(HttpContext context, Exception exception) { var code = HttpStatusCode.InternalServerError; var exceptionDto = new ExceptionDto { Message = exception.Message, Source = exception.Source, StackTrace = exception.StackTrace }; var result = JsonConvert.SerializeObject(exceptionDto); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); }
public void Log(Exception e, ISystemProcess process) { if (process == null) { this.Log(e); return; } var dto = new ExceptionDto { ExceptionMessage = e.Message, InnerExceptionMessage = e.InnerException?.Message, StackTrace = e.StackTrace, SystemProcessId = process?.Id }; this._exceptionRepository.Save(dto); }
internal static async Task <HttpContext> SetResponse(this HttpContext httpContext, int statusCode, string message) { httpContext.Response.Clear(); httpContext.Response.StatusCode = statusCode; httpContext.Response.ContentType = @"application/json"; var response = new ExceptionDto(message); var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var jsonResponse = JsonConvert.SerializeObject(response, serializerSettings); await httpContext.Response.WriteAsync(jsonResponse, Encoding.UTF8); return(httpContext); }
public static ApiExceptionDto CreateApiErrorException(this Exception exception, int httpStatusCode) { var exceptionDto = new ExceptionDto { Message = exception.Message, Source = exception.Source, StackTrace = exception.StackTrace }; var apiErrorException = new ApiExceptionDto { HttpStatusCode = httpStatusCode, Exception = exceptionDto }; return(apiErrorException); }
public void ExceptionSavesToDatabase() { var config = new SystemDataLayerConfig { SurveillanceAuroraConnectionString = "server=127.0.0.1; port=3306;uid=root;pwd='drunkrabbit101';database=dev_surveillance; Allow User Variables=True" }; var repository = new ExceptionRepository(new ConnectionStringFactory(config), this._logger); var dtos = new ExceptionDto { ExceptionMessage = "hello world", InnerExceptionMessage = "Goodbye world", StackTrace = "a/b/c", SystemProcessId = "0", SystemProcessOperationId = 1 }; repository.Save(dtos); }
public void Log(Exception e, ISystemProcessOperation operation) { if (operation == null) { this.Log(e); return; } var dto = new ExceptionDto { ExceptionMessage = e.Message, InnerExceptionMessage = e.InnerException?.Message, StackTrace = e.StackTrace, SystemProcessOperationId = operation.Id, SystemProcessId = operation.SystemProcessId }; this._exceptionRepository.Save(dto); }
/// <inheritdoc/> public void Log(object entry) { if (!IsOutputEnabled) { return; } LogEntry logEntry = StdJsonLogging.NormalizeToLogEntry(entry, SerializerSource); string dotNetTypePrefix = logEntry.DotNetType == null ? string.Empty : $"{logEntry.DotNetType}: "; WriteLine( $"{logEntry.Instant.InZone(_localZone):hh:mm:ss.f}: {dotNetTypePrefix}{logEntry.Message}"); if (logEntry.Exception != null) { var baseIntent = " |"; Write(baseIntent); WriteLine( "------------------------------------- Exception ---------------------------------------"); string intent = string.Empty; ExceptionDto curException = logEntry.Exception; do { Write(baseIntent); Write(intent); if (intent != string.Empty) { Write("<--"); } string name = curException.TypeFullName?.Split('.')?.Last() ?? "NullName"; WriteLine($"{name}: {curException.Message}"); curException = curException.InnerException; intent += " "; }while (curException != null); Write(baseIntent); WriteLine( "---------------------------------------------------------------------------------------"); } }
public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder applicationBuilder) { applicationBuilder.UseExceptionHandler(errorApp => { errorApp.Run(async context => { Exception error = context.Features.Get <IExceptionHandlerPathFeature>()?.Error; context.Response.StatusCode = error is DomainException exception ? (int)ExceptionCodeToHttpStatusCodeMap[exception.ExceptionCode] : (int)HttpStatusCode.InternalServerError; ExceptionDto dto = error.ToExceptionDto(); context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Json; await context.Response.WriteAsync(JsonSerializer.Serialize(dto, DefaultResponseJsonSerializerOptions.Options)); }); }); return(applicationBuilder); }
public void Log(Exception e, ISystemProcessOperationThirdPartyDataRequest request) { if (request == null) { this.Log(e); return; } var dto = new ExceptionDto { ExceptionMessage = e.Message, InnerExceptionMessage = e.InnerException?.Message, StackTrace = e.StackTrace, SystemProcessId = request.SystemProcessId, SystemProcessOperationId = request.SystemProcessOperationId, SystemProcessOperationThirdPartyDataRequestId = request.Id }; this._exceptionRepository.Save(dto); }
public void Log(Exception e, ISystemProcessOperationUploadFile uploadRule) { if (uploadRule == null) { this.Log(e); return; } var dto = new ExceptionDto { ExceptionMessage = e.Message, InnerExceptionMessage = e.InnerException?.Message, StackTrace = e.StackTrace, SystemProcessOperationUploadFileRuleId = uploadRule.Id, SystemProcessOperationId = uploadRule.SystemProcessOperationId, SystemProcessId = uploadRule.SystemProcessId }; this._exceptionRepository.Save(dto); }
protected void ResetSessionWorker(RemoteCodeSession session, WorkerResetReason reason) { Logger.LogLine($"Worker Reset: {session.SessionId}"); session.WorkerClient?.Close(); Logger.LogLine($"Worker Reset: closed worker socket of {session.SessionId}"); try { if (session.WorkerProcess?.HasExited == false) { session.WorkerProcess?.Kill(); Logger.LogLine($"Worker Reset: killed worker process of {session.SessionId}"); //notify client of worker destruction if (reason == WorkerResetReason.Expired && //don't notify if worker is no longer executing user code session.LastAppState != RemoteAppState.NotRunning && session.LastAppState != RemoteAppState.Ended && session.LastAppState != RemoteAppState.Crashed ) { clientService.SendExecutionState(session.SessionId, new ExecutionStateDto { SessionId = session.SessionId, State = RemoteAppState.Crashed, Exception = ExceptionDto.FromException(new TimeoutException( $"Your application takes longer than {SessionConstants.SessionIdleTimeout} seconds to execute and has been terminated.")) }); } } } finally { session.WorkerClient?.Dispose(); session.WorkerProcess?.Dispose(); session.WorkerProcess = null; session.WorkerClient = null; } }
private static ExceptionDto ToExceptionDto(this Exception exception) { if (exception is null) { return(null); } ExceptionDto dto = new ExceptionDto { Message = exception.Message, }; if (exception is DomainException domainException) { dto.ExceptionCode = domainException.ExceptionCode; if (domainException is DomainValidationException validationException) { dto.ValidationErros = validationException.ValidationErrors; } } return(dto); }
public async Task <IHttpActionResult> Call(ExceptionDto logDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Log log = new Log() { Deter = Determiner.Exception, ContractId = "None", UseType = "Error", Response = false, UserType = logDto.UserType, UserName = logDto.UserName, Message = logDto.Message, CreationDate = DateTime.Now }; var res = CheckLog(log); if (res != null) { return(new System.Web.Http.Results.ResponseMessageResult( Request.CreateErrorResponse( (HttpStatusCode)422, new HttpError($"Error in Log : {res} must contain a value") ) )); } db.Logs.Add(log); await db.SaveChangesAsync(); return(StatusCode(HttpStatusCode.OK)); }
public NewPasswordNotMatchException() { ExceptionDto = new ExceptionDto("NewPasswordNotMatchException", "La nueva contraseña no coincide con la verificación"); }
public UserOnlyAdminException() { ExceptionDto = new ExceptionDto("UserOnlyAdminException", "Debe asignar otro administrador para poder salir del grupo familiar"); }
/// <inheritdoc /> public override async Task Consume(IConsumingContext consumingContext) { _lastMsgTime = DateTime.Now; var consumedMessage = consumingContext.GetMessage <TMsgPayload>(); var logger = consumingContext.GetLogger <MqBatchConsumer <TMsgPayload, TLogic> >(); _lastLogger = logger; _lastLogic = _singletonLogic ?? consumingContext.CreateLogic <TLogic>(); _lastConsumingContext = consumingContext; logger.Debug("Input mq message") .AndFactIs("queue", Queue) .AndFactIs("msg-id", consumedMessage.MessageId) .AndLabel("batch-consumer") .Write(); _messages.Add(consumedMessage); if (_messages.Count >= BatchSize) { logger.Debug("Perform consuming") .AndFactIs("queue", Queue) .AndFactIs("msg-count", _messages.Count) .AndLabel("sync-mq-batch-processing") .Write(); await PerformConsumingAsync(); } if (_monitorTask != null) { ExceptionDto exDto = null; if (_monitorTask.Exception != null) { exDto = ExceptionDto.Create(_monitorTask.Exception); } logger.Debug("Monitor task state") .AndFactIs("Status", _monitorTask.Status) .AndFactIs("IsCompleted", _monitorTask.IsCompleted) .AndFactIs("IsCompletedSuccessfully", _monitorTask.IsCompletedSuccessfully) .AndFactIs("IsFaulted", _monitorTask.IsFaulted) .AndFactIs("IsCanceled", _monitorTask.IsCanceled) .AndFactIs("Exception", exDto ?? (object)"no-exception") .Write(); } _monitorTask ??= Task.Run(Async); //try //{ // logger.Debug("Monitor task state") // .AndFactIs("task", _monitorTask) // .Write(); //} //catch (Exception e) //{ // Console.WriteLine(e); // throw; //} }
public FamilyNotAceptedSolicitudeException() { ExceptionDto = new ExceptionDto("FamilyNotAceptedSolicitudeException", "El grupo familiar no acepta solicitudes"); }
private static ExceptionInfo CreatExceptionInfo(ExceptionDto dto) { return dto == null ? null : ExceptionInfo.Create(dto.Message, dto.Source, dto.StackTrace, CreatExceptionInfo(dto.InnerException)); }
public void RunApplication(string sessionid, TcpClient client, byte[] assemblyBytes) { var networkStream = client.GetStream(); var outputRedirector = new ConsoleOutputService(sessionid, client); var inputRedirector = new ConsoleInputService(sessionid, client); ExecutionStateDto execState; var assembly = Assembly.Load(assemblyBytes); try { execState = new ExecutionStateDto { SessionId = sessionid, State = RemoteAppState.Running }; networkStream.WriteByte((byte)MessageType.WorkerExecutionState); Serializer.SerializeWithLengthPrefix(networkStream, execState, PrefixStyle.Fixed32); Logger.LogLine($"CLIENT: sent execution state {execState.State}"); //redirect console Console.SetOut(outputRedirector); Console.SetIn(inputRedirector); //invoke main method var mainParms = assembly.EntryPoint.GetParameters(); if (mainParms.Count() == 0) { assembly.EntryPoint.Invoke(null, null); } else { if (mainParms[0].ParameterType == typeof(string[])) { assembly.EntryPoint.Invoke(null, new string[] { null }); } else { assembly.EntryPoint.Invoke(null, null); } } //reset console redirection Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); Console.SetIn(new StreamReader(Console.OpenStandardInput())); execState = new ExecutionStateDto { SessionId = sessionid, State = RemoteAppState.Ended }; networkStream.WriteByte((byte)MessageType.WorkerExecutionState); Serializer.SerializeWithLengthPrefix(networkStream, execState, PrefixStyle.Fixed32); Logger.LogLine($"CLIENT: sent execution state {execState.State}"); } catch (SocketException socketEx) { Logger.LogLine($"CLIENT Error: {socketEx.Message}"); } catch (Exception ex) { execState = new ExecutionStateDto { SessionId = sessionid, State = RemoteAppState.Crashed, Exception = ExceptionDto.FromException(ex) }; networkStream.WriteByte((byte)MessageType.WorkerExecutionState); Serializer.SerializeWithLengthPrefix(networkStream, execState, PrefixStyle.Fixed32); } finally { } }
public UserFamilyNotFoundException() { ExceptionDto = new ExceptionDto("UserFamilyNotFoundException", "El usuario no pertenece a una familia"); }
public ActualPasswordNotMatchException() { ExceptionDto = new ExceptionDto("ActualPasswordNotMatchException", "La actual contraseña no coincide"); }
public StockRequestNotFoundException() { ExceptionDto = new ExceptionDto("StockRequestNotFoundException", "No se ha encontrado bajo los parametros requeridos"); }
public SolicitudeTroubleException() { ExceptionDto = new ExceptionDto("SolicitudeTroubleException", "Ha ocurrido un problema al realizar su operacion"); }
public UserNotAdminException() { ExceptionDto = new ExceptionDto("UserNotAdminException", "Usuario no reconocido como administrador"); }