4

This is a sample ApiController used

[RequestExceptionFilter]
public class RequestController : ApiController
{
    public IHttpActionResult Post([FromBody]Request RequestDTO)
    {
        //some code over here
        throw new DTONullException(typeof(Request.Models.DTO.Request));

This is my custom exception handler

public class RequestExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        { 
            if (context.Exception is DTONullException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("DTO is null"),
                    ReasonPhrase = "DTO is null",
                };
            }

            base.OnException(context);
        }
    }

And while debugging, I get this error:

An exception of type 'Request.Controllers.DTONullException' occurred in Request.dll but was not handled in user code

enter image description here

Should I use the try-catch syntax here ? What is the convention ?

In all the samples I see in the internet, people just throw the exception but they dont seem to catch it.

(Ofcourse, If i press Run, the application returns a BadRequest as expected but the question is should i use try-catch or just leave the code above as such ?)

  • `Based on the answer below` and `http://stackoverflow.com/questions/58380/avoiding-first-chance-exception-messages-when-the-exception-is-safely-handled`, this is a normal behaviour. – now he who must not be named. Jun 17 '14 at 14:13
  • And in addition to this, I referred `http://stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon` for understanding deeper. – now he who must not be named. Jun 17 '14 at 14:15

1 Answers1

3

The only reliable way of catching exceptions in ASP.NET (no matter if you are using WebForms/MVC/WebApi) is the Application_Error event in global.asax.

The exception that you demonstrated can however be caught with IExceptionHandler.

class OopsExceptionHandler : ExceptionHandler
{
    public override void HandleCore(ExceptionHandlerContext context)
    {
        context.Result = new TextPlainErrorResult
        {
            Request = context.ExceptionContext.Request,
            Content = "Oops! Sorry! Something went wrong." +
                      "Please contact support@contoso.com so we can try to fix it."
        };
    }

    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = 
                             new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent(Content);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
}

and in your webapi2 config add the following:

config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());
jgauffin
  • 95,399
  • 41
  • 227
  • 352
  • 1
    Thank you. But I think the question is different one. I am asking `how to throw exceptions`. I have already implemented a `custom exception`, `a exception filter attribute`. The question is, `is it just enough to use a throw statement` to throw the exception ? (I am asking this because I am receiving a error "`the exception is not handled in the user-code`" as in the screen-shot) – now he who must not be named. Jun 17 '14 at 13:36
  • 1
    you do not have to use try/catch – jgauffin Jun 17 '14 at 13:38
  • So, it is fine that the error appearing during debug ? I can skip that error. correct ? – now he who must not be named. Jun 17 '14 at 13:41
  • 1
    yes, press F5 and your handler will take care of it. It's called first chance exceptions and is a debugging feature. – jgauffin Jun 17 '14 at 14:09