简体   繁体   中英

Custom exceptions - Am I doing it right?

I am currently writing a .net REST web api, and am using custom exceptions so that I can send back detailed information to the client as well as the correct http response to stay compliant with REST.. but it seems like I am explicitly throwing a lot of exceptions.

For example: I have an API for uploading image files. These image files have to be a certain file format and under a certain size. If my code finds that an image is the wrong file format, I throw a new custom exception like:

throw new FileTypeException();

Or, if the file is too big, meaning the file.Size() is greater than an amount I have set in the web.config, I throw a different custom exception like:

throw new FileSizeException();

I then catch these exceptions in my Post() method and return a 400 BadRequest and a reason.

So, my code is not actually throwing an error, its just the request does not meet specifications. Is this bad practice?

This might be more appropriate as a Programming question rather than Stack Overflow.

Throwing custom exceptions can be very useful in the right scenario, and a lot of unnecessary work and complexity in the wrong scenario. Usually the sanity check I use, is different handling for each distinct exception type.

For example, your FileTypeException and FileSizeException - is there a different catch for each type? Or are you just returning a different message?

If it's the latter, try to consolidate where you can or use the framework provided exceptions. If it's the former, then you're using custom exceptions right.

An exception filter works great for these cases. In your WebApiConfig, register an exception filter

config.Filters.Add(new CustomExceptionFilterAttribute());

Code for a basic filter:

//needed for CreateErrorResponse(statusCode, message)
using System.Net.Http

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        //you can get the underlying exception here
        var type = context.Exception.GetType();

        //I like to map exception types to status codes
        var statusCode = GetHttpStatusCode(type);

        //respond with a proper status code and the message
        context.Response = context.Request.CreateErrorResponse(statusCode, context.Exception.Message);
    }
}

Now in any controller code you can throw and it will hit your filter

public IHttpActionResult Get(int id)
{
    throw new FileSizeException();
}

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