Catching exceptions in web api - Should I use a try-catch statement?

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 ?)

Upvotes: 4

Views: 7453

Answers (1)

jgauffin
jgauffin

Reputation: 101130

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 [email protected] 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());

Upvotes: 4

Related Questions