官术网_书友最值得收藏!

Error handling

In the previous chapter, we saw how to redirect to specific actions when an error occurs. Another option could be to leverage the IExceptionFilter and IAsyncExceptionFilter interfaces, one of the filter classes, to have the controller itself—or some other class—implement error handling directly.

In our controller, it's just a matter of implementing theIExceptionFilterclass, which only has one method,OnException:

public void OnException(ExceptionContext context)
{
var ex = context.Exception;

//do something with the exception

//mark it as handled, so that it does not propagate
context.ExceptionHandled = true;
}

In the asynchronous version, IAsyncExceptionFilter, the OnExceptionAsync method takes the same parameter but must return a Task.

In Chapter 10, Understanding Filters, we will learn more about the concept of filters. For now, it is enough to say that should any exception be thrown from an action in a controller implementing IExceptionFilter, its OnException method will be called.

Don't forget to set ExceptionHandled to true if you don't want the exception to propagate!

The next topic is related to performance: response caching.

主站蜘蛛池模板: 富民县| 本溪| 离岛区| 达尔| 大化| 湘潭县| 博乐市| 卢氏县| 苗栗市| 明光市| 温州市| 正蓝旗| 黄浦区| 曲靖市| 永州市| 都昌县| 休宁县| 酉阳| 尼勒克县| 昭苏县| 嵊州市| 禄劝| 白河县| 深州市| 杭锦后旗| 丰台区| 淮阳县| 连江县| 沙湾县| 霍邱县| 邢台市| 台江县| 周宁县| 阿尔山市| 汤阴县| 天柱县| 景宁| 科尔| 云南省| 晋中市| 宜川县|