我對@mythz' answer做了改進。
public override void Configure(Container container) {
//Handle Exceptions occurring in Services:
this.ServiceExceptionHandlers.Add((httpReq, request, exception) = > {
//log your exceptions here
...
//call default exception handler or prepare your own custom response
return DtoUtils.CreateErrorResponse(request, exception);
});
//Handle Unhandled Exceptions occurring outside of Services
//E.g. Exceptions during Request binding or in filters:
this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) = > {
res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
#if !DEBUG
var message = "An unexpected error occurred."; // Because we don't want to expose our internal information to the outside world.
#else
var message = ex.Message;
#endif
res.WriteErrorToResponse(req, req.ContentType, operationName, message, ex, ex.ToStatusCode()); // Because we don't want to return a 200 status code on an unhandled exception.
});
}
我擔心這會很麻煩。如果我只想修改非服務異常的HTTP狀態代碼,該怎麼辦?我可以在某處評估每個異常並設置它的HTTP狀態代碼嗎? – 2013-03-24 22:55:37
您可以訪問'res' HttpResponse,以便您可以設置您想要的任何響應屬性。閱讀錯誤頁面瞭解如何將異常映射到狀態代碼。 – mythz 2013-03-24 23:09:34
好的,我明白了。再次感謝您的幫助! – 2013-03-24 23:45:56