public override void OnActionExecuting(ActionExecutingContext context) { RoleLevelEnum?roleEnum; try { string roleLevel = GetClaimValue(context.HttpContext, "Role"); roleEnum = Enum.Parse <RoleLevelEnum>(roleLevel); } catch { context.HttpContext.Response.StatusCode = ErrorCodes.Unauthorized.GetHashCode();; context.Result = new JsonResult(ExceptionPayload.New(new UnauthorizedException())); return; } var permissions = Roles.ToList().Contains(roleEnum.Value); if (!permissions) { context.HttpContext.Response.StatusCode = ErrorCodes.Forbidden.GetHashCode(); context.Result = new JsonResult(ExceptionPayload.New(new ForbiddenException())); return; } base.OnActionExecuting(context); }
protected IHttpActionResult HandleFailure <T>(T exceptionToHandle) where T : Exception { ExceptionPayload exceptionPayload = ExceptionPayload.New(exceptionToHandle); return(exceptionToHandle is BusinessException? Content(HttpStatusCode.BadRequest, exceptionPayload) : Content(HttpStatusCode.InternalServerError, exceptionPayload)); }
/// <summary> /// Estrutura uma resposta http com a exceção disparada no <paramref name="context"/> /// </summary> /// <param name="context"></param> /// <returns></returns> public static HttpResponseMessage HandleExecutedContextException(this HttpActionExecutedContext context) { var exceptionPayload = ExceptionPayload.New(context.Exception); return(context.Exception is BusinessException? context.Request.CreateResponse(HttpStatusCode.BadRequest, exceptionPayload) : context.Request.CreateResponse(HttpStatusCode.InternalServerError, exceptionPayload)); }
protected IHttpActionResult HandleFailure <T>(T exceptionToHandle) where T : Exception { var exceptionPayload = ExceptionPayload.Novo(exceptionToHandle); return(exceptionToHandle is ExcecaoDeNegocio? Content(HttpStatusCode.BadRequest, exceptionPayload) : Content(HttpStatusCode.InternalServerError, exceptionPayload)); }
/// <summary> /// Extension Method do HttpActionExecutedContext para manipular o context quando há uma exceção /// e retornar um ExceptionPayload customizado, informando ao client o que houve de errado. /// /// </summary> /// <param name="context">É o context atual da requisição</param> /// <returns>HttpResponseMessage contendo a exceção</returns> public static HttpResponseMessage HandleExecutedContextException(this HttpActionExecutedContext context) { // Retorna a resposta para o cliente com o erro 500 ou 400 e o ExceptionPayload (código de erro de negócio e message) var exceptionPayload = ExceptionPayload.New(context.Exception); return(context.Exception is BusinessException? context.Request.CreateResponse(HttpStatusCode.BadRequest, exceptionPayload) : context.Request.CreateResponse(HttpStatusCode.InternalServerError, exceptionPayload)); }
public ResponsePayload(ResponseVersionInfo versionInfo, object data, ExceptionPayload exception, string rolesInfo) { this.VersionInfo = versionInfo; this.Data = data; this.Exception = exception; this.RolesInfo = rolesInfo; }
protected IActionResult HandleFailure <T>(T exceptionToHandle) where T : Exception { if (exceptionToHandle is ValidationException) { return(StatusCode(HttpStatusCode.BadRequest.GetHashCode(), (exceptionToHandle as ValidationException).Errors)); } var exceptionPayload = ExceptionPayload.New(exceptionToHandle); return(exceptionToHandle is BusinessException? StatusCode(exceptionPayload.ErrorCode.GetHashCode(), exceptionPayload) : StatusCode(HttpStatusCode.InternalServerError.GetHashCode(), exceptionPayload)); }
/// <summary> /// Log the last exception in a parseable format to serilog. /// </summary> /// <param name="exception">The exception to log.</param> /// <param name="context">Additional context.</param> public static void LogException(Exception exception, string context) { try { var payload = new ExceptionPayload { Context = context, When = DateTime.Now, Info = exception.ToString(), }; var encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload))); Log.Information($"LASTEXCEPTION:{encodedPayload}"); } catch (Exception ex) { Log.Error(ex, "Could not print exception."); } }
protected ExceptionPayload GetExceptionPayload(Exception ex) { if (ex == null) { return(null); } var payload = new ExceptionPayload(); payload.Message = ex.Message; var exType = ex.GetType(); foreach (var mapping in BaseExceptionsTypesMapping) { if (mapping.First.IsAssignableFrom(exType)) { payload.Name = mapping.Second; if (BaseExceptionsWithSpecificTypes.Contains(mapping.First)) { OSException osException = ex as OSException; if (osException != null) { payload.SpecificType = osException.GetUniqueName(); } else { payload.SpecificType = exType.FullName; } } break; } } if (payload.Name == null) { throw new InvalidOperationException("Failed to find exception mapping for " + exType.Name); } return(payload); }
/// <summary> /// Log the last exception in a parseable format to serilog. /// </summary> /// <param name="exception">The exception to log.</param> /// <param name="context">Additional context.</param> public static void LogException(Exception exception, string context) { LastException = exception; try { var fixedContext = context?.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); var payload = new ExceptionPayload { Context = fixedContext, When = DateTime.Now, Info = exception.ToString(), }; var encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload))); Log.Information($"LASTEXCEPTION:{encodedPayload}"); } catch (Exception) { Log.Error("Could not print exception"); } }
protected IHttpActionResult GetScreenServiceResult(HttpStatusCode status, object dataPayload, Payload.ResponseVersionInfo versionInfo, ExceptionPayload exception, MobileLoginInfoEndpoint loginEndpoint, HeContext context) { var hasNewRuntimeSession = context != null && context.Session != null && context.Session.HasNewRuntimeSessionStorage; return(GetScreenServiceResult(status, dataPayload, versionInfo, exception, loginEndpoint, hasNewRuntimeSession ? context.Session.NewRuntimeLoginInfo : null, hasNewRuntimeSession ? context.Session.GetRolesInfo() : null)); }
public FailResponsePayload(ExceptionPayload exception) { this.Exception = exception; }
/// <summary> /// Extension Method do HttpActionExecutedContext para manipular o context quando há uma exceção /// e retornar um ExceptionPayload customizado, informando ao client o que houve de errado. /// /// </summary> /// <param name="context">É o contexto atual da requisição</param> /// <returns>HttpResponseMessage contendo a exceção</returns> public static HttpResponseMessage HandleExecutedContextException(this HttpActionExecutedContext context) { // Retorna a resposta para o cliente com o erro 500 e o ExceptionPayload (código de erro de negócio e mensagem) return(context.Request.CreateResponse(HttpStatusCode.InternalServerError, ExceptionPayload.New(context.Exception))); }
// TODO JMR Remove this method and merge it with the above overload when the Obsolete overload is removed private IHttpActionResult GetScreenServiceResult(HttpStatusCode status, object dataPayload, Payload.ResponseVersionInfo versionInfo, ExceptionPayload exception, MobileLoginInfoEndpoint loginEndpoint, LoginInfo loginInfo, Func <string> rolesInfo) { var responseMessage = new HttpResponseMessage(status); string rolesInfoserialized = null; if (loginEndpoint != null && loginInfo != null) { if (rolesInfo != null) { rolesInfoserialized = loginInfo.UpdateRolesHashAndCalculateRolesInfo(rolesInfo()); } loginEndpoint.WriteLoginInfoToResponse(loginInfo); } responseMessage.Content = new ObjectContent(typeof(Payload.ResponsePayload), new Payload.ResponsePayload(versionInfo, dataPayload, exception, rolesInfoserialized), JsonMediaTypeFormater); RestServiceHttpUtils.AddNoCacheHeaders(responseMessage); if (DebuggerHelper.IsRunning) { if (DebuggerHelper.StopImmediately) { RestServiceHttpUtils.AddCustomHeader(responseMessage, StopImmediatelyHeaderName, DebuggerHelper.StopImmediately.ToString()); } else if (DebuggerHelper.RunToBreakpoint != null) { RestServiceHttpUtils.AddCustomHeader(responseMessage, RunToBreakpointHeaderName, DebuggerHelper.RunToBreakpoint.ToString(true)); } } return(ResponseMessage(responseMessage)); }
public static HttpResponseMessage HandleExecutedContextException(this HttpActionExecutedContext context) { return(context.Request.CreateResponse(HttpStatusCode.InternalServerError, ExceptionPayload.New(context.Exception))); }
public override void OnException(ExceptionContext context) { context.Exception = context.Exception; context.HttpContext.Response.StatusCode = 500; context.Result = new JsonResult(ExceptionPayload.New(context.Exception)); }
protected IHttpActionResult GetScreenServiceResult(HttpStatusCode status, ExceptionPayload exception) { return(GetScreenServiceResult(status, null, null, exception, null, null, null)); }