Exemplo n.º 1
0
        public override void OnException(ExceptionContext context)
        {
            LogException(context);
            if (context.HttpContext.Request.Path.ToString().StartsWith("/api"))
            {
                var result = ApiErrorHandler.HandleApiException(context.HttpContext.User, context.Exception);
                if (result.exceptionHandled)
                {
                    context.ExceptionHandled = true;

                    var objectResult = new ObjectResult(result.message);
                    objectResult.StatusCode = result.statusCode;

                    context.Result = objectResult;
                }
            }
            else
            {
                var result = MvcErrorHandler.HandleException(context.HttpContext.User, context.Exception);
                if (result.exceptionHandled)
                {
                    context.ExceptionHandled = true;
                    context.Result           = result.result;
                }
            }
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(options =>
                {
                    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Haru ga Kita!");
                });
            }
            else
            {
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseExceptionHandler(error =>
            {
                error.Run(async context =>
                {
                    await Task.Run(() =>
                    {
                        var apiErrorHandler = new ApiErrorHandler(context);
                        apiErrorHandler.Handle();
                    });
                });
            });
            app.UseMvc();
        }
Exemplo n.º 3
0
        /*/// <summary>
         * /// Async method that allows you to send arbitrary strings to server
         * /// </summary>
         * /// <param name="value">The arbitrary string to be sent to the server</param>
         * /// <param name="connectedToInternet">Flag for whether an internet connection is present. A <exception cref="NotConnectedToInternetException">NotConnectedToInternetException exception is throw if value is false</exception></param>
         * /// <returns>ServerResponseObjectsBase on success or null on failure</returns>
         * [Obsolete("ServerResponseObjectsBase is an unneeded class and will be removed, as will this method that has a dependancy on it. Use MakeGetCallAsync instead")]
         * protected async Task<ServerResponseObjectsBase> GetStringAsync(string value, bool connectedToInternet)
         * {
         *  string url = string.Format(GetCallsBasePath, value);
         *  var client = DefaultClient;
         *  foreach (KeyValuePair<string, string> headers in extraHeaders)
         *  {
         *      client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
         *  }
         *
         *  HttpResponseMessage responseMsg = null;
         *
         *  try
         *  {
         *      if (!connectedToInternet)
         *      {
         *          throw new NotConnectedToInternetException();
         *      }
         *
         *      responseMsg = await client.GetAsync(await this.AddLocationAndLanguageToApi(url));
         *
         *      string result = responseMsg.Content.ReadAsStringAsync().Result;
         *      if (responseMsg.IsSuccessStatusCode == false)
         *      {
         *          throw new Exception(result);
         *      }
         *
         *      return new ServerResponseObjectsBase
         *      {
         *          RawResponseText = result,
         *          StatusCode = responseMsg.StatusCode,
         *          IsSuccessStatus = responseMsg.IsSuccessStatusCode
         *      };
         *  }
         *  catch (Exception ex)
         *  {
         *      Debug.WriteLine("Call error was " + ex.Message);
         *      return new ServerResponseObjectsBase
         *      {
         *          IsSuccessStatus = false,
         *          RequestException = ex,
         *          StatusCode = responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
         *          RawResponseText = "{}"
         *      };
         *  }
         * }*/

        /// <summary>
        /// Async method that allows you to send arbitrary JSON string to server
        /// </summary>
        /// <param name="jsonString">The arbitrary JSON string to be sent to the server</param>
        /// <param name="successCallback">The success callback</param>
        /// <param name="filterFlags">Error handling filter flags</param>
        /// <param name="timeOut">Time out in milliseconds</param>
        /// <returns>JSON string on success or null on failure</returns>
        protected async Task <ServerResponseObjectsBase> PostStringAsync(string jsonString, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;
            HttpResponseMessage responseMsg = null;
            var client = this.DefaultClient;

            foreach (KeyValuePair <string, string> headers in this._extraHeaders)
            {
                client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
            }

            try
            {
                string url = await this.AddLocationAndLanguageToApi(this.ApiPath);

                responseMsg = await client.PostAsync(url, new StringContent(jsonString, Encoding.UTF8, @"application/json"));

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);
                string rawResponse = await responseMsg.Content.ReadAsStringAsync();

                rawResponse.WriteLine();
                var resp = new ServerResponseObjectsBase
                {
                    RawResponseText = await responseMsg.Content.ReadAsStringAsync(),
                    StatusCode      = responseMsg.StatusCode,
                    IsSuccessStatus = responseMsg.IsSuccessStatusCode
                };

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(resp.RawResponseText, null);
                }

                if (successCallback != null)
                {
                    successCallback(resp);
                }

                return(resp);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await this.PostStringAsync(jsonString, successCallback),
                    successCallback);

                return(new ServerResponseObjectsBase
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    StatusCode = responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
                    RawResponseText = "{}"
                });
            }
        }
Exemplo n.º 4
0
 public PatientController(LabTestRequestsData labTestRequestsData,
                          ApiErrorHandler apiErrorHandler,
                          IMapper mapper,
                          PatientNoteData patientNoteData,
                          PatientData patientData,
                          UserData userData,
                          PatientProgressData patientProgressData)
 {
     _labTestRequestsData = labTestRequestsData;
     _apiErrorHandler     = apiErrorHandler;
     _mapper              = mapper;
     _patientNoteData     = patientNoteData;
     _patientData         = patientData;
     _userData            = userData;
     _patientProgressData = patientProgressData;
 }
Exemplo n.º 5
0
        internal static IApplicationBuilder UseErrorHandling(this IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async(context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    await ApiErrorHandler.HandleExceptionAsync(app, context, ex, env);
                }
            });

            return(app);
        }
        public override void OnException(ExceptionContext context)
        {
            ApiError apiError = null;

            // Handle Errors thru the chain
            ErrorHandler apiErrorHanler           = new ApiErrorHandler();
            ErrorHandler unauthorizedErrorHandler = new UnauthorizedErrorHandler();
            ErrorHandler unhandledErrorHandler    = new UnhandledErrorHandler();

            // Set Handlers
            apiErrorHanler.SetNextHandler(unauthorizedErrorHandler);
            unauthorizedErrorHandler.SetNextHandler(unhandledErrorHandler);

            // Hanle
            apiErrorHanler.Handle(context, apiError);

            base.OnException(context);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Method to send specific JSON String to the server and wait for a response
        /// </summary>
        /// <typeparam name="TR">Response type</typeparam>
        /// <param name="jsonString">JSON payload</param>
        /// <param name="successCallback">Success callback</param>
        /// <param name="filterFlags">Error handling flags</param>
        /// <param name="timeOut">Timeout in seconds</param>
        /// <returns>The server response</returns>
        public async Task <ServerResponse <TR> > PostJsonAsync <TR>(string jsonString, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;
            HttpResponseMessage responseMsg = null;

            this.Logger.Debug("Passed Json is as below");
            this.Logger.Debug(jsonString);
            try
            {
                // add all extra headers, if any
                HttpClient httpClient = this.DefaultClient;

                foreach (KeyValuePair <string, string> headers in this._extraHeaders)
                {
                    httpClient.DefaultRequestHeaders.Add(headers.Key, headers.Value);
                }

                string url = await this.AddLocationAndLanguageToApi(this.ApiPath);

                StringContent content = new StringContent(jsonString, Encoding.UTF8, @"application/json");

                // check internet connection
                if (!Resolver.Instance.Get <IConnectivityService>().HasConnection())
                {
                    throw new NotConnectedToInternetException();
                }

                responseMsg = await httpClient.PostAsync(url, content);

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);

                var resp = new ServerResponse <TR>
                {
                    RawResponse     = await responseMsg.Content.ReadAsStringAsync(),
                    StatusCode      = responseMsg.StatusCode,
                    IsSuccessStatus = responseMsg.IsSuccessStatusCode
                };

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(resp.RawResponse, resp.GetObject());
                }

                if (successCallback != null)
                {
                    successCallback(resp);
                }

                return(resp);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await PostJsonAsync <TR>(jsonString, successCallback),
                    successCallback);

                return(new ServerResponse <TR>
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    StatusCode =
                        responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
                    RawResponse = "{}"
                });
            }
            finally
            {
                this.Logger.Debug("Exiting PostJsonAsync");
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Makes get calls to the server.
        /// </summary>
        /// <typeparam name="TR">The expected return type</typeparam>
        /// <param name="value">Additional query parameters</param>
        /// <param name="successCallback">A method to be called on success</param>
        /// <param name="filterFlags">The API error filter flags</param>
        /// <param name="timeOut">Timeout in seconds</param>
        /// <returns>Server response that provides information on success/failure of the call and also encapsulates the returned object</returns>
        /// <exception cref="NotConnectedToInternetException">Throws an NotConnectedToInternetException if not connected to the internet when an API call is made</exception>
        /// <exception cref="Exception">Throw a System.Exception for any other error that occurs during processing</exception>
        public virtual async Task <ServerResponse <TR> > MakeGetCallAsync <TR>(string value, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;

            string url = string.Format(this.GetCallsBasePath, value);

            Logger.Verbose("Url " + url);

            var client = this.DefaultClient;

            foreach (KeyValuePair <string, string> headers in this._extraHeaders)
            {
                client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
            }

            HttpResponseMessage responseMsg = null;

            try
            {
                if (!Resolver.Instance.Get <IConnectivityService>().HasConnection())
                {
                    throw new NotConnectedToInternetException();
                }

                responseMsg = await client.GetAsync(await this.AddLocationAndLanguageToApi(url));

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);
                var result = await this.GetServerResponsePackaged <TR>(responseMsg);

                if (filterFlags == ErrorFilterFlags.Ignore204)
                {
                    filterFlags = ErrorFilterFlags.AllowEmptyResponses;
                }

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(result.RawResponse, result.GetObject());
                }

                if (successCallback != null)
                {
                    successCallback(result);
                }

                return(result);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await this.MakeGetCallAsync <TR>(value, successCallback, filterFlags),
                    successCallback);

                return(new ServerResponse <TR>()
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    Status = ServiceReturnStatus.ServerError
                });
            }
        }
Exemplo n.º 9
0
        public async Task <CustomerRegistrationResponse> RegisterCustomer(Customer customer, ApiTimeoutEnum timeOut)
        {
            // register custom error handler for 500 error, we want to show toast and continue
            var errorDescriber500 = new ErrorDescriber(
                typeof(HttpResponse500Exception),
                typeof(BackgroundNotifier),
                ErrorFilterFlags.Ignore500Family);

            ApiErrorHandler.RegisterExpectedError(this, errorDescriber500);

            Log.Verbose("Register Customer.");
            ServerResponse <CustomerRegistrationResponse> response =
                await this.PostObjectAsync <CustomerRegistrationResponse, Customer>(customer, timeOut : timeOut);

            Log.Verbose("API call done.");
            if (response == null)
            {
                Log.Verbose("API NOT successfull");

                return(new CustomerRegistrationResponse()
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = null
                });
            }

            Log.Verbose("API result: " + response.IsSuccessStatus);
            Log.Verbose(response.RawResponse);

            // try getting the object from JSON
            CustomerRegistrationResponse result = null;

            try
            {
                result = response.GetObject();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

            // got a proper result, return it
            if (result != null)
            {
                result.Successful = true;
                return(result);
            }

            Log.Verbose("Could not parse response.");

            // 500 error occured, special case
            if (response.RequestException.GetType().IsAssignableFrom(typeof(HttpResponse500Exception)))
            {
                return(new CustomerRegistrationResponse
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = "HttpResponse500Exception"
                });
            }

            // if exception was thrown, return the exception as text
            if (response.RequestException != null)
            {
                return(new CustomerRegistrationResponse
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = response.RequestException.ToString()
                });
            }

            // unknown error returned
            return(new CustomerRegistrationResponse
            {
                Customer = null,
                RequestId = customer.RequestId,
                Successful = false,
                ResponseText = "Unknown Error."
            });
        }
Exemplo n.º 10
0
 protected override void OnResume()
 {
     base.OnResume();
     ApiErrorHandler.SetErrorOccuredCallback(this.ErrorOccuredCallback);
     SalesApplication.IsInBackground = false;
 }
Exemplo n.º 11
0
 protected override void OnPause()
 {
     base.OnPause();
     SalesApplication.IsInBackground = true;
     ApiErrorHandler.UnsetCallbacks();
 }