ロギングとか
MVC4でさくさくサービスを書いてるんだが、どうしてもちょっとしたミスで例外が出てたりしてその原因究明に追われたりするのはご愛嬌みたいなもんで。
しかし、いつまでもこんな状況なのも大変アレなのでまずはUnhandledExceptionを捕まえてログにきちんと吐かせるようにしようと。
UnhandledExceptionの捕まえ方
デスクトップアプリならApplication.ThreadExceptionハンドラあたりで捕まえればいいんだけど。
MVCだとControllerかFilterにイベントがあるんかなと調べたら大体ビンゴ。
The OnException Method The System.Web.Mvc.Controller class contains a method called OnException which is called whenever an exception occuts within an action. This does not rely on the HandleError attribute being set. If you're being a good coder and have your own base Controller class you can override this method in one place to handle/log all errors for your site.
ASP.NET MVC HandleError Attribute, Custom Error Pages and Logging Exceptions
Controller.OnExceptionをオーバーライドしてそこにロギングコードを埋めればいいと。
しかし、沢山あるコントローラーに一々コードを埋めるのも馬鹿らしいので、継承にサンドイッチコードでブチ込むことに。
public class ErrorHandledController : Controller { protected override void OnException(ExceptionContext filterContext) { // Output a nice error page ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Error(filterContext.Exception); if (filterContext.HttpContext.IsCustomErrorEnabled) { filterContext.ExceptionHandled = true; this.View("Error").ExecuteResult(this.ControllerContext); } else { base.OnException(filterContext); } } }
大変ダサい。