简体   繁体   中英

Global exception handling WebApi 2 , Having trouble with HTTPPOST

I am trying to handle exceptions globally. Here goes my exceptionHandlerClass

   public override void Handle(ExceptionHandlerContext context)
    {
        HttpResponseMessage resp;
        resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent(context.Exception.Message),
            ReasonPhrase = context.Exception.Message
        };
        context.Result = new ErrorMessageResult(context.Request, resp);
    }
}
public class ErrorMessageResult : IHttpActionResult
{
    private readonly HttpResponseMessage _httpResponseMessage;
    private HttpRequestMessage _request;

    public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
    {
        _request = request;
        _httpResponseMessage = httpResponseMessage;
    }
}

registered exception handler in WebApiConfig.cs

   config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

Below are the actions in the controller for httppost and httpget

   [Route("ArgumentNull/{id}")]
    [HttpPost]
    public IHttpActionResult ArgumentNull(int id)
    {
        Report objModel = new Report();
        objModel.ThrowItemNotFoundException();
        return Ok();
    }
    [Route("ArgumentNull/{id}")]
    [HttpGet]
    public IHttpActionResult ArgumentNullGet(int id)
    {
        Report objModel = new Report();
        objModel.ThrowItemNotFoundException();
        return Ok();
    }

So the response for httpget is caught in the globalExceptionHandler class but httpPost just throws me error back with stack trace(unwanted information), can someone please let me know if i am missing soemthing.

It appears your GlobalExceptionHandler class implements ExceptionHandler, which has the method ShouldHandle. This method returns false when the Request Method is POST or PUT, among other scenarios. To fix this consider overriding the method to return true:

public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;                        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM