3

In my WebAPI 2.1 application I am processing inserts like this:

    [Route("Post")]
    public async Task<IHttpActionResult> Post([FromBody]City city)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            db.Exams.Add(city);
            await db.SaveChangesAsync(User, DateTime.UtcNow);
        }
        catch (Exception ex)
        {
            var e = ex;
            return BadRequest("Error: City not created");
        }
        return Ok(city);
    }

I use something similar for updates and deletes. I think I should do something more meaningfull with the exceptions but I am not sure where to start with how to handle these. I looked at elmah but it said it deals with unhandled exceptions. Does this mean I should not be catching exceptions like this?

Can someone give me some pointers as to if what I have is okay and also should I be logging exceptions and how?

1 Answer 1

3

What you are doing is not "bad", it's just a bit verbose and won't scale well if you have many try/catch blocks all over your code. When an exception is raised, you decide what to do so, returning a bad request response is fine if it's really a bad request. There are many things you can return, depending on what went wrong. But you have to handle what to do when exceptions are thrown all over your code, so maintaining this logic scattered all over your code can quickly become a problem.

It's better to utilise asp.net web api's exception handling framework. For example, take a look at these articles:

The idea is to centralise your logic in a global exception handler and to use that as the only place in your code where you have to worry about this. The rest of your code will be throwing exceptions and everything will be coming through your exception handler/filter/etc., depending on what you decide.

For example, I have created my own exception types (e.g. CustomExceptionA, CustomExceptionB, etc.) and when I throw an exception of a type I know exactly how to handle it in one place and perform a certain bit of logic. If I want to change the way I handle a particular exception type, then there's only one place I have to make a change and the rest of the code will be unaffected.

The second article link above also includes a global exception logger to log such exceptions.

Sign up to request clarification or add additional context in comments.

Comments