/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public virtual Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { var info = ExceptionDispatchInfo.Capture(context.Exception); info.Throw(); return Task.FromResult(0); }
public override void Handle(ExceptionHandlerContext context) { HttpRequestMessage request = context.Request; context.Result = new ResponseMessageResult(request.CreateResponse(HttpStatusCode.InternalServerError, new ErrorMsg(context.Exception.Message))); }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { // For exceptions at the top of the call stack, Result will start out non-null (due to // LastChanceExceptionHandler). This class does not force exceptions back to unhandled in such cases, so it // will not not trigger the host-level exception processing, such as the ASP.NET yellow screen. return TaskHelpers.Completed(); }
private static async Task<HttpResponseMessage> HandleAsyncCore(IExceptionHandler handler, ExceptionHandlerContext context, CancellationToken cancellationToken) { Contract.Assert(handler != null); Contract.Assert(context != null); await handler.HandleAsync(context, cancellationToken); IHttpActionResult result = context.Result; if (result == null) { return null; } HttpResponseMessage response = await result.ExecuteAsync(cancellationToken); if (response == null) { throw new InvalidOperationException(Error.Format(SRResources.TypeMethodMustNotReturnNull, typeof(IHttpActionResult).Name, "ExecuteAsync")); } return response; }
public virtual bool ShouldHandle(ExceptionHandlerContext context) { //WebAPI v2 does not use IsOutermostCatchBlock anymore //IsOutermostCatchBlock does not exists. Use CatchBlock.IsTopLevel instead: //http://stackoverflow.com/a/22357634/1616023 return context.ExceptionContext.CatchBlock.IsTopLevel; }
private static void Handle(ExceptionHandlerContext context) { if (context == null) { throw new ArgumentNullException("context"); } ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); Exception exception = exceptionContext.Exception; HttpRequestMessage request = exceptionContext.Request; if (request == null) { throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull, typeof(ExceptionContext).Name, "Request"), "context"); } if (exceptionContext.CatchBlock == ExceptionCatchBlocks.IExceptionFilter) { // The exception filter stage propagates unhandled exceptions by default (when no filter handles the // exception). return; } context.Result = new ResponseMessageResult(request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception)); }
public override void Handle(ExceptionHandlerContext context) { var exception = context.Exception; var httpException = exception as HttpException; if (httpException != null) { context.Result = new SimpleErrorResult(context.Request, (HttpStatusCode)httpException.GetHttpCode(), httpException.Message); return; } if (exception is RootObjectNotFoundException) { context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.NotFound, exception.Message); return; } if (exception is ChildObjectNotFoundException) { context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.Conflict, exception.Message); return; } context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.InternalServerError, exception.Message); }
private void HandleValidationException(ExceptionHandlerContext context) { context.Result = new GlobalExceptionResponse(context.ExceptionContext.Request, HttpStatusCode.BadRequest) { Message = context.Exception.Message }; }
public override void Handle(ExceptionHandlerContext context) { if (context.Exception is Code.ExceptionResponse) { Code.ExceptionResponse ex = context.Exception as Code.ExceptionResponse; context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = Transfer.Response.Error(ex.Message) }; } else if (context.Exception is Code.ExceptionMaintenance) { context.Result = new TextPlainErrorResult { Content = Transfer.Response.Maintenance("Server is down for maintenance") }; } else { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = Transfer.Response.Error(context.Exception.Message) }; } }
public override void Handle(ExceptionHandlerContext context) { bool shouldHandle = this.ShouldHandle(context); if (!shouldHandle) { return; } ErrorContext errorContext = null; try { errorContext = ErrorContextService.Resolve(context); var model = new ErrorViewModel(errorContext, context.RequestContext.RouteData.Values); var jsonModel = model.ToJson(); var response = context.Request.CreateResponse(errorContext.HttpStatusCode, jsonModel); context.Result = new ResponseMessageResult(response); } finally { ErrorContextService.Log(CurrentLogger, errorContext); } }
// Create the error info object to be returned to the requestor public override void Handle(ExceptionHandlerContext context) { context.Result = new ResponseMessageResult (context.Request.CreateResponse(HttpStatusCode.InternalServerError, new ErrorInfo { Message = context.Exception.Message, Timestamp = DateTime.Now })); }
/// <summary> /// Format the result of the error context to be send back. /// </summary> /// <param name="context"></param> public override void Handle(ExceptionHandlerContext context) { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = $"We apologize but an unexpected error occurred. Please try again later. {context.Exception.Message}" }; }
//public override void Handle(ExceptionHandlerContext context) //{ // context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.BadRequest, context.Exception.Message)); //} public override void Handle(ExceptionHandlerContext context) { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = context.Exception.Message }; }
/// <summary> /// 在衍生類別中覆寫時,同步處理例外狀況。 /// </summary> /// <param name="context">例外狀況處理常式內容。</param> public override void Handle(ExceptionHandlerContext context) { ICustomExceptionHandler exceptionHandler = ExceptionHelper.GetExceptionType(context); context.Result = new ResponseMessageResult(exceptionHandler.ExceptionMessage(context)); base.Handle(context); }
public override void Handle(ExceptionHandlerContext context) { context.Result = new PlainExceptionResult { Request = context.ExceptionContext.Request, Exception = context.Exception }; }
public override void Handle(ExceptionHandlerContext context) { // get base exception var baseExp = context.Exception.GetBaseException(); // set the result context.Result = new InternalServerErrorPlainTextResult(baseExp.Message, context.Request); }
/// <summary> /// 在衍生類別中覆寫時,同步處理例外狀況。 /// </summary> /// <param name="context">例外狀況處理常式內容。</param> public override void Handle(ExceptionHandlerContext context) { IError error = ErrorFactory.GetExceptionType(context); context.Result = new ResponseMessageResult(error.GenerateExceptionMessage(context)); base.Handle(context); }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { var jsonResult = "Error Global"; context.Result = new ResponseMessageResult(new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(jsonResult) }); return Task.FromResult(0); }
public override void HandleCore(ExceptionHandlerContext context) { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = "Oops! Something went wrong." }; }
/// <summary> /// Gets the type of the exception. /// </summary> /// <param name="context">The context.</param> /// <returns>ICustomExceptionHandler</returns> public static ICustomExceptionHandler GetExceptionType(ExceptionHandlerContext context) { var exceptionType = ExceptionCategory .FirstOrDefault(x => x.ExceptionType .Equals(context.Exception.GetType().Name)); return exceptionType ?? new OtherCategory(); }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (context.CatchBlock != ExceptionCatchBlocks.HttpServer) { context.Result = null; } return Task.FromResult(0); }
/// <summary> /// Gets the type of the exception. /// </summary> /// <param name="context">The context.</param> /// <returns>ICustomExceptionHandler</returns> public static IError GetExceptionType(ExceptionHandlerContext context) { var exceptionType = ExceptionCategory .FirstOrDefault(x => x.ExceptionType .Equals(context.Exception.GetType().Name)); return exceptionType ?? new UnexpectError(); }
public override void Handle(ExceptionHandlerContext context) { _logger.Error("Unhandled error occured during route {0}. Error {1}", context.Request.RequestUri, context.Exception.Message); context.Result = new GeneralErrorResult { Request = context.ExceptionContext.Request, Content = "An error has occurred on the server. Please contact support!" }; }
private void HandleAuthenticationException(ExceptionHandlerContext context) { var credentials = context.ParseAuthorizationHeader(); Logger.Warn($"Api {context.Request.Method} {context.Request.RequestUri} unauthenticated request!"); var authHeader = credentials != null ? context.ExceptionContext.Request.Headers.Authorization : new AuthenticationHeaderValue("Basic", "id:password".ToBase64String()); context.Result = new UnauthorizedResult(new[] { authHeader }, context.ExceptionContext.Request); }
public override void Handle(ExceptionHandlerContext context) { //context.Result = context.ExceptionContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "oops!"); context.Result = new ErrorResult { Request = context.ExceptionContext.Request, Content = "Something bad happend!" }; }
public override void Handle(ExceptionHandlerContext context) { var errorInformation = new ErrorInformation() { Message = "An unhandled exception occurred; check the log for more information.", }; context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.BadRequest, errorInformation)); }
private ExceptionHandlerContext GetAuthorizedExceptionContext(AuthenticationHeaderValue authHeader) { var ex = new Exception(); var catchBlock = new ExceptionContextCatchBlock("catch", false, false); var context = new ExceptionHandlerContext(new ExceptionContext(ex, catchBlock)); context.ExceptionContext.Request = new HttpRequestMessage(); context.ExceptionContext.Request.Headers.Authorization = authHeader; return context; }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (!ShouldHandle(context)) { return Task.FromResult(0); } return HandleAsyncCore(context, cancellationToken); }
public override void Handle(ExceptionHandlerContext context) { Debug.WriteLine("Handling"); context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = ErrorMessage }; }
public override void Handle(ExceptionHandlerContext context) { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = ConfigurationManager.AppSettings["defaultErrorMessage"] }; _logger.Log(LogLevel.Error, context.Exception.Message, context.Exception); }
public void HandleAsync_IfRequestIsNull_Throws() { // Arrange IExceptionHandler product = CreateProductUnderTest(); ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext { Exception = CreateException() }); Assert.Null(context.ExceptionContext.Request); // Guard CancellationToken cancellationToken = CancellationToken.None; // Act & Assert Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), "context", "ExceptionContext.Request must not be null."); }
public void ShouldHandle_IfCallStackIsNull_Throws() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler>(); mock.CallBase = true; ExceptionHandler product = mock.Object; ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext()); Assert.Null(context.ExceptionContext.CatchBlock); // Guard // Act & Assert Assert.ThrowsArgument(() => product.ShouldHandle(context), "context", "ExceptionContext.CatchBlock must not be null."); }
public void ExceptionGet_ReturnsSpecifiedInstance() { // Arrange Exception expectedException = new InvalidOperationException(); ExceptionContext context = new ExceptionContext( expectedException, ExceptionCatchBlocks.HttpServer ); ExceptionHandlerContext product = CreateProductUnderTest(context); // Act Exception exception = product.Exception; // Assert Assert.Same(expectedException, exception); }
public async Task HandleAsyncCore_DelegatesToHandleCore_AndReturnsCompletedTask() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler>(); mock.CallBase = true; ExceptionHandler product = mock.Object; ExceptionHandlerContext expectedContext = CreateMinimalValidHandlerContext(); CancellationToken cancellationToken = CancellationToken.None; // Act await product.HandleAsync(expectedContext, cancellationToken); // Assert mock.Verify(h => h.Handle(expectedContext), Times.Once()); }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (context != null) { ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); ExceptionContextCatchBlock catchBlock = exceptionContext.CatchBlock; if (catchBlock != null && catchBlock.IsTopLevel) { context.Result = CreateDefaultLastChanceResult(exceptionContext); } } return(_innerHandler.HandleAsync(context, cancellationToken)); }
public async Task HandleAsync_IfCatchBlockIsIExceptionFilter_LeavesExceptionUnhandled() { IExceptionHandler product = CreateProductUnderTest(); // Arrange using (HttpRequestMessage request = CreateRequest()) { ExceptionHandlerContext context = CreateValidContext(request, ExceptionCatchBlocks.IExceptionFilter); CancellationToken cancellationToken = CancellationToken.None; // Act await product.HandleAsync(context, cancellationToken); // Assert Assert.Null(context.Result); } }
public void HandleAsync_IfContextIsNull_Throws() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler> { CallBase = true }; IExceptionHandler product = mock.Object; ExceptionHandlerContext context = null; CancellationToken cancellationToken = CancellationToken.None; // Act & Assert Assert.ThrowsArgumentNull( () => product.HandleAsync(context, cancellationToken), "context" ); }
/// <summary>Calls an exception handler and determines the response handling it, if any.</summary> /// <param name="handler">The unhandled exception handler.</param> /// <param name="context">The exception context.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns> /// A task that, when completed, contains the response message to return when the exception is handled, or /// <see langword="null"/> when the exception remains unhandled. /// </returns> public static Task <HttpResponseMessage> HandleAsync(this IExceptionHandler handler, ExceptionContext context, CancellationToken cancellationToken) { if (handler == null) { throw new ArgumentNullException("handler"); } if (context == null) { throw new ArgumentNullException("context"); } ExceptionHandlerContext handlerContext = new ExceptionHandlerContext(context); return(HandleAsyncCore(handler, handlerContext, cancellationToken)); }
public void CatchBlockGet_ReturnsSpecifiedInstance() { // Arrange ExceptionContextCatchBlock expectedCatchBlock = new ExceptionContextCatchBlock( "IgnoreName", false, false ); ExceptionContext context = new ExceptionContext(new Exception(), expectedCatchBlock); ExceptionHandlerContext product = CreateProductUnderTest(context); // Act ExceptionContextCatchBlock catchBlock = product.CatchBlock; // Assert Assert.Same(expectedCatchBlock, catchBlock); }
public void ShouldHandle_ReturnsIsTopLevelCatchBlock(bool isTopLevelCatchBlock) { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler>(); mock.CallBase = true; ExceptionHandler product = mock.Object; ExceptionHandlerContext context = CreateContext(new ExceptionContext(new Exception(), new ExceptionContextCatchBlock("IgnoreCaughtAt", isTopLevelCatchBlock, callsHandler: false))); // Act bool shouldHandle = product.ShouldHandle(context); // Assert Assert.Equal(isTopLevelCatchBlock, shouldHandle); }
/// <inheritdoc /> Task IExceptionHandler.HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException("context"); } ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); if (!ShouldHandle(context)) { return(TaskHelpers.Completed()); } return(HandleAsync(context, cancellationToken)); }
public void HandleAsync_IfCatchBlockIsIExceptionFilter_LeavesExceptionUnhandled() { IExceptionHandler product = CreateProductUnderTest(); // Arrange using (HttpRequestMessage request = CreateRequest()) { ExceptionHandlerContext context = CreateValidContext(request, ExceptionCatchBlocks.IExceptionFilter); CancellationToken cancellationToken = CancellationToken.None; // Act Task task = product.HandleAsync(context, cancellationToken); task.WaitUntilCompleted(); // Assert Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.Null(context.Result); } }
/// <summary>Determines whether the exception should be handled.</summary> /// <param name="context">The exception handler context.</param> /// <returns> /// <see langword="true"/> if the exception should be handled; otherwise, <see langword="false"/>. /// </returns> /// <remarks>The default decision is only to handle exceptions caught at top-level catch blocks.</remarks> public virtual bool ShouldHandle(ExceptionHandlerContext context) { if (context == null) { throw new ArgumentNullException("context"); } ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); ExceptionContextCatchBlock catchBlock = exceptionContext.CatchBlock; if (catchBlock == null) { throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull, typeof(ExceptionContext), "CatchBlock"), "context"); } return(catchBlock.IsTopLevel); }
public void HandleAsyncCore_DelegatesToHandleCore_AndReturnsCompletedTask() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler>(); mock.CallBase = true; ExceptionHandler product = mock.Object; ExceptionHandlerContext expectedContext = CreateContext(); CancellationToken cancellationToken = CancellationToken.None; // Act Task task = product.HandleAsync(expectedContext, cancellationToken); // Assert Assert.NotNull(task); task.WaitUntilCompleted(); Assert.Equal(TaskStatus.RanToCompletion, task.Status); mock.Verify(h => h.Handle(expectedContext), Times.Once()); }
public async Task HandleAsync_HandlesExceptionViaCreateErrorResponse() { IExceptionHandler product = CreateProductUnderTest(); // Arrange using (HttpRequestMessage expectedRequest = CreateRequest()) { expectedRequest.SetRequestContext( new HttpRequestContext { IncludeErrorDetail = true } ); ExceptionHandlerContext context = CreateValidContext(expectedRequest); CancellationToken cancellationToken = CancellationToken.None; // Act await product.HandleAsync(context, cancellationToken); // Assert IHttpActionResult result = context.Result; ResponseMessageResult typedResult = Assert.IsType <ResponseMessageResult>(result); using (HttpResponseMessage response = typedResult.Response) { Assert.NotNull(response); using ( HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse( HttpStatusCode.InternalServerError, context.ExceptionContext.Exception ) ) { AssertErrorResponse(expectedResponse, response); } Assert.Same(expectedRequest, response.RequestMessage); } } }
public void HandleAsync_IfShouldHandleReturnsTrue_DelegatesToHandleAsyncCore() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler> { CallBase = true }; Task expectedTask = CreateCompletedTask(); mock.Setup(h => h.ShouldHandle(It.IsAny <ExceptionHandlerContext>())).Returns(true); mock.Setup( h => h.HandleAsync( It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>() ) ) .Returns(expectedTask); IExceptionHandler product = mock.Object; ExceptionHandlerContext expectedContext = CreateMinimalValidHandlerContext(); using (CancellationTokenSource tokenSource = CreateTokenSource()) { CancellationToken expectedCancellationToken = tokenSource.Token; // Act Task task = product.HandleAsync(expectedContext, expectedCancellationToken); // Assert Assert.Same(expectedTask, task); mock.Verify(h => h.ShouldHandle(expectedContext), Times.Once()); mock.Verify( h => h.HandleAsync(expectedContext, expectedCancellationToken), Times.Once() ); } }
private static void Handle(ExceptionHandlerContext context) { if (context == null) { throw new ArgumentNullException("context"); } ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); Exception exception = exceptionContext.Exception; HttpRequestMessage request = exceptionContext.Request; if (request == null) { throw new ArgumentException( Error.Format( SRResources.TypePropertyMustNotBeNull, typeof(ExceptionContext).Name, "Request" ), "context" ); } if (exceptionContext.CatchBlock == ExceptionCatchBlocks.IExceptionFilter) { // The exception filter stage propagates unhandled exceptions by default (when no filter handles the // exception). return; } context.Result = new ResponseMessageResult( request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception) ); }
/// <inheritdoc /> Task IExceptionHandler.HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException("context"); } ExceptionContext exceptionContext = context.ExceptionContext; Contract.Assert(exceptionContext != null); if (exceptionContext.Exception == null) { throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull, typeof(ExceptionContext).Name, "Exception"), "context"); } if (!ShouldHandle(context)) { return(TaskHelpers.Completed()); } return(HandleAsync(context, cancellationToken)); }
public void HandleAsync_HandlesExceptionViaCreateErrorResponse() { IExceptionHandler product = CreateProductUnderTest(); // Arrange using (HttpRequestMessage expectedRequest = CreateRequest()) { expectedRequest.SetRequestContext(new HttpRequestContext { IncludeErrorDetail = true }); ExceptionHandlerContext context = CreateValidContext(expectedRequest); CancellationToken cancellationToken = CancellationToken.None; // Act Task task = product.HandleAsync(context, cancellationToken); task.WaitUntilCompleted(); // Assert Assert.Equal(TaskStatus.RanToCompletion, task.Status); IHttpActionResult result = context.Result; Assert.IsType(typeof(ResponseMessageResult), result); ResponseMessageResult typedResult = (ResponseMessageResult)result; using (HttpResponseMessage response = typedResult.Response) { Assert.NotNull(response); using (HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse( HttpStatusCode.InternalServerError, context.ExceptionContext.Exception)) { AssertErrorResponse(expectedResponse, response); } Assert.Same(expectedRequest, response.RequestMessage); } } }
private static async Task TestHandleAsyncLeavesResultNull(ExceptionHandlerContext context) { Mock <IExceptionHandler> mock = new Mock <IExceptionHandler>(MockBehavior.Strict); IHttpActionResult result = null; mock .Setup(h => h.HandleAsync(It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>())) .Returns <ExceptionHandlerContext, CancellationToken>((c, i) => { result = c != null ? c.Result : null; return(Task.FromResult(0)); }); IExceptionHandler innerHander = mock.Object; IExceptionHandler product = CreateProductUnderTest(innerHander); CancellationToken cancellationToken = CancellationToken.None; // Act await product.HandleAsync(context, cancellationToken); // Assert Assert.Null(result); }
public void HandleAsync_IfShouldHandleReturnsFalse_ReturnsCompletedTask() { // Arrange Mock <ExceptionHandler> mock = new Mock <ExceptionHandler>(MockBehavior.Strict); Task expectedTask = CreateCompletedTask(); mock.Setup(h => h.ShouldHandle(It.IsAny <ExceptionHandlerContext>())).Returns(false); IExceptionHandler product = mock.Object; ExceptionHandlerContext expectedContext = CreateValidContext(); CancellationToken expectedCancellationToken = CancellationToken.None; // Act Task task = product.HandleAsync(expectedContext, expectedCancellationToken); // Assert Assert.NotNull(task); Assert.True(task.IsCompleted); Assert.Equal(TaskStatus.RanToCompletion, task.Status); mock.Verify(h => h.ShouldHandle(expectedContext), Times.Once()); mock.Verify(h => h.HandleAsync(It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>()), Times.Never()); }
/// <summary>When overridden in a derived class, handles the exception synchronously.</summary> /// <param name="context">The exception handler context.</param> public virtual void Handle(ExceptionHandlerContext context) { }
public virtual void HandleCore(System.Web.Http.ExceptionHandling.ExceptionHandlerContext context) { }
public virtual Task HandleAsyncCore(System.Web.Http.ExceptionHandling.ExceptionHandlerContext context, CancellationToken cancellationToken) { HandleCore(context); return(Task.FromResult(0)); }
/// <summary> /// Handles the <paramref name="context"/> asynchronously. /// </summary> /// <param name="context"></param> /// <param name="token"></param> /// <returns></returns> public Task HandleAsync(ExceptionHandlerContext context, CancellationToken token) { return(Task.Run(() => { }, token)); }
public async Task HandleAsync_IfIsTopLevelCatchBlockAndCanCreateExceptionResult_InitializesResult( bool includeDetail ) { Mock <IExceptionHandler> mock = new Mock <IExceptionHandler>(MockBehavior.Strict); IHttpActionResult result = null; mock.Setup( h => h.HandleAsync( It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>() ) ) .Returns <ExceptionHandlerContext, CancellationToken>( (c, i) => { result = c != null ? c.Result : null; return(Task.FromResult(0)); } ); IExceptionHandler innerHander = mock.Object; IExceptionHandler product = CreateProductUnderTest(innerHander); Exception expectedException = CreateDummyException(); IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator(); using (HttpConfiguration configuration = CreateConfiguration()) using (HttpRequestMessage expectedRequest = CreateRequest()) { configuration.Services.Replace( typeof(IContentNegotiator), expectedContentNegotiator ); configuration.Formatters.Clear(); MediaTypeFormatter expectedFormatter = CreateDummyFormatter(); configuration.Formatters.Add(expectedFormatter); ExceptionHandlerContext context = new ExceptionHandlerContext( new ExceptionContext( exception: expectedException, catchBlock: CreateTopLevelCatchBlock(), request: expectedRequest ) { RequestContext = new HttpRequestContext { Configuration = configuration, IncludeErrorDetail = includeDetail }, } ); CancellationToken cancellationToken = CancellationToken.None; // Act await product.HandleAsync(context, cancellationToken); // Assert ExceptionResult exceptionResult = Assert.IsType <ExceptionResult>(result); Assert.Same(expectedException, exceptionResult.Exception); Assert.Equal(includeDetail, exceptionResult.IncludeErrorDetail); Assert.Same(expectedContentNegotiator, exceptionResult.ContentNegotiator); Assert.Same(expectedRequest, exceptionResult.Request); Assert.NotNull(exceptionResult.Formatters); MediaTypeFormatter formatter = Assert.Single(exceptionResult.Formatters); Assert.Same(expectedFormatter, formatter); } }
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { Handle(context); return(TaskHelpers.Completed()); }