ASP.NET MVC, throw HttpException vs return HttpStatusCodeResult?

后端 未结 4 1032
情书的邮戳
情书的邮戳 2020-12-24 10:47

I am developing a RESTful service and I want to return 400 for all unsupported URLs.

My question is when should I choose method 1 over method 2 and vice-vers

4条回答
  •  眼角桃花
    2020-12-24 11:11

    Although this question is a bit old I figured I'd give my input since I came across this.

    Errors are values. This goes for an HttpException (when unthrown) as well as an HttpStatusCodeResult. Thrown exceptions, however, create new code paths that are hidden away from your coworkers that may be one execution context higher up than yours and have to be given documentation that these code paths will be passed to them without notice. Values, however, tell you everything you need to know through their type. You can use their type in the expected execution path to tell whether an error has occured as well as find associated information with that error and log it.

    I sometimes use (lightly extended) Exception's without throwing them to the next execution context to extract the useful debug information that David Rodriguez mentioned. There's never an excuse to be handing thrown exceptions to execution contexts above you that aren't actually exceptional, and this only really applies to things that are actually outside of your code's ability to handle (StackOverflowException, other fatal system exceptions, etc).

    In a networked application, such as whatever MVC service you're running, the performance penalty from throwing exceptions is meaningless. The semantics and effects on maintainability, are not.

    Network errors are values, and you should handle them like so.

提交回复
热议问题