Пример #1
0
 /// <summary>
 /// 处理在服务之外抛出的异常
 /// </summary>
 /// <param name="httpRequest"></param>
 /// <param name="httpResponse"></param>
 /// <param name="operationName"></param>
 /// <param name="exception"></param>
 public void OnHandleUncaughtException(
     IHttpRequest httpRequest, IHttpResponse httpResponse, string operationName, System.Exception exception)
 {
     httpResponse.Write("Error: {0}: {1}".Fmt(exception.GetType().Name, exception.Message));
     httpResponse.EndRequest(skipHeaders: true);
     DtoUtils.HandleException(_appHost, httpResponse, exception);
 }
Пример #2
0
        public override void Configure(Container container)
        {
            JsConfig.DateHandler        = JsonDateHandler.ISO8601;
            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new RazorFormat());
            Plugins.Add(new CorsFeature());

            SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                               },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                    { "Access-Control-Allow-Headers", "Content-Type"                    },
                },
                DebugMode            = true,
                DefaultContentType   = ContentType.Json,
                AllowJsonpRequests   = true,
                DefaultRedirectPath  = "/stats",
                MetadataRedirectPath = "/stats",
                MetadataCustomPath   = "/stats"
            });


            //Unhandled exceptions
            //Handle Exceptions occurring in Services:

            this.ServiceExceptionHandler = (request, exception) => {
                //log your exceptions here
                Logger.LogDebug("ServiceExceptionHandler : " + exception.Message, exception.StackTrace);

                //call default exception handler or prepare your own custom response
                return(DtoUtils.HandleException(this, request, exception));
            };

            //Handle Unhandled Exceptions occurring outside of Services,
            //E.g. in Request binding or filters:
            this.ExceptionHandler = (req, res, operationName, ex) =>
            {
                Logger.LogDebug("ExceptionHandler : " + ex.Message, ex.StackTrace);
                res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                res.EndServiceStackRequest(skipHeaders: true);
            };

            /**
             * Note: since Mono by default doesn't have any trusted certificates is better to validate them in the app domain
             * than to add them manually to the deployment server
             */
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
            {
                return(true);    //Todo: fix this to actually validate the certificates
            };

            Plugins.Add(new SwaggerFeature());

            InitGateway();
        }
Пример #3
0
        /// <summary>
        /// Override the built-in Exception handling
        /// </summary>
        /// <param name="request"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        protected virtual object HandleException(TRequest request, Exception ex)
        {
            var errorResponse = ServiceExceptionHandler != null
                ? ServiceExceptionHandler(request, ex)
                : DtoUtils.HandleException(GetResolver(), request, ex);

            AfterEachRequest(request, errorResponse ?? ex);

            return(errorResponse);
        }
Пример #4
0
        public static object HandleException(IResolver resolver, object request, Exception ex)
        {
            var validationException = ex as ValidationException;

            if (validationException != null)
            {
                var errors = validationException.Errors.ConvertAll(x =>
                                                                   new ValidationErrorField(x.ErrorCode, x.PropertyName, x.ErrorMessage));

                return(DtoUtils.CreateErrorResponse(typeof(ValidationException).Name, validationException.Message, errors));
            }

            return(DtoUtils.HandleException(resolver, request, ex));
        }
 public override object HandleException(IRequestContext requestContext, T request, Exception ex)
 {
     if (isYourCondition)
     {
         ResponseStatus rs = new ResponseStatus("YourException", "your_log");
         // optionally if anybody wants custom response errors
         rs.Errors = new List <ResponseError>();
         rs.Errors.Add(new ResponseError());
         rs.Errors[0].ErrorCode = "testCode123";
         // create errorResponse with the custom responseStatus
         var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs);
         // log the error
         DtoUtils.HandleException(AppHost, request, ex);
         return(errorResponse);
     }
     else
     {
         return(base.HandleException(requestContext, request, ex));
     }
 }
Пример #6
0
        public object ExecutePath(
            string httpMethod,
            string pathInfo,
            Dictionary <string, string> queryString,
            Dictionary <string, string> formData,
            string requestBody)
        {
            var httpHandler = GetHandler(httpMethod, pathInfo);

            var contentType = (formData != null && formData.Count > 0)
                ? MimeTypes.FormUrlEncoded
                : requestBody != null ? MimeTypes.Json : null;

            var httpReq = new MockHttpRequest(
                httpHandler.RequestName, httpMethod, contentType,
                pathInfo,
                queryString.ToNameValueCollection(),
                requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
                formData.ToNameValueCollection()
                );

            var    request = httpHandler.CreateRequest(httpReq, httpHandler.RequestName);
            object response;

            try
            {
                response = httpHandler.GetResponse(httpReq, null, request);
            }
            catch (Exception ex)
            {
                response = DtoUtils.HandleException(AppHost, request, ex);
            }

            var httpRes = response as IHttpResult;

            if (httpRes != null)
            {
                var httpError = httpRes as IHttpError;
                if (httpError != null)
                {
                    throw new WebServiceException(httpError.Message)
                          {
                              StatusCode  = httpError.Status,
                              ResponseDto = httpError.Response
                          };
                }
                var hasResponseStatus = httpRes.Response as IHasResponseStatus;
                if (hasResponseStatus != null)
                {
                    var status = hasResponseStatus.ResponseStatus;
                    if (status != null && !status.ErrorCode.IsNullOrEmpty())
                    {
                        throw new WebServiceException(status.Message)
                              {
                                  StatusCode  = (int)HttpStatusCode.InternalServerError,
                                  ResponseDto = httpRes.Response,
                              };
                    }
                }

                return(httpRes.Response);
            }

            return(response);
        }
Пример #7
0
        public override void Configure(Container container)
        {
            JsConfig.DateHandler        = JsonDateHandler.ISO8601;
            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new RazorFormat());

            SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                      },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE" },
                    { "Access-Control-Allow-Headers", "Content-Type"           },
                },
                DebugMode            = true,
                DefaultContentType   = ContentType.Json,
                AllowJsonpRequests   = true,
                DefaultRedirectPath  = "/stats",
                MetadataRedirectPath = "/stats",
                MetadataCustomPath   = "/stats"
            });


            //Authentication
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new CustomCredentialsAuthProvider()
            }
                                        )
            {
                HtmlRedirect  = "~/login.html",
                ServiceRoutes = new Dictionary <Type, string[]> {
                    { typeof(AuthService), new[] { "/auth", "/auth/{provider}" } },
                    { typeof(AssignRolesService), new[] { "/assignroles" } },
                    { typeof(UnAssignRolesService), new[] { "/unassignroles" } },
                }
            }
                        );

            //Unhandled exceptions
            //Handle Exceptions occurring in Services:
            this.ServiceExceptionHandler = (request, exception) => {
                //log your exceptions here
                Logger.LogDebug("ServiceExceptionHandler : " + exception.Message, exception.StackTrace);

                //call default exception handler or prepare your own custom response
                return(DtoUtils.HandleException(this, request, exception));
            };

            //Handle Unhandled Exceptions occurring outside of Services,
            //E.g. in Request binding or filters:
            this.ExceptionHandler = (req, res, operationName, ex) =>
            {
                Logger.LogDebug("ExceptionHandler : " + ex.Message, ex.StackTrace);
                res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                res.EndServiceStackRequest(skipHeaders: true);
            };

            /**
             * Note: since Mono by default doesn't have any trusted certificates is better to validate them in the app domain
             * than to add them manually to the deployment server
             */
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
            {
                return(true);    //Todo: fix this to actually validate the certificates
            };

            //Init
            using (var initPartners = container.Resolve <InitGatewayService>())
            {
                initPartners.Any(null);
            }

            Plugins.Add(new SwaggerFeature());
        }
Пример #8
0
 /// <summary>
 /// 处理在服务内部抛出的异常
 /// </summary>
 /// <param name="httpRequest"></param>
 /// <param name="request"></param>
 /// <param name="exception"></param>
 /// <returns></returns>
 public object OnServiceExceptionHandler(
     IHttpRequest httpRequest, object request, System.Exception exception)
 {
     return(DtoUtils.HandleException(_appHost, request, exception));
 }
 public override object HandleException(IRequestContext requestContext, T request, System.Exception ex)
 {
     return(DtoUtils.HandleException(new BasicResolver(), request, ex));
 }