简体   繁体   English

自定义例外-我做对了吗?

[英]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. 我目前正在编写.net REST网络api,并且正在使用自定义异常,以便可以将详细信息以及正确的http响应发送回客户端,以保持与REST的兼容性。.但是看来我在明确抛出很多例外。

For example: I have an API for uploading image files. 例如:我有一个用于上传图像文件的API。 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: 或者,如果文件太大,则意味着file.Size()大于我在web.config中设置的数量,那么我将抛出另一个自定义异常,例如:

throw new FileSizeException();

I then catch these exceptions in my Post() method and return a 400 BadRequest and a reason. 然后,我在Post()方法中捕获这些异常,并返回400 BadRequest和一个原因。

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? 例如,您的FileTypeException和FileSizeException-每种类型都有不同的catch吗? 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 在您的WebApiConfig中,注册一个异常过滤器

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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