ServiceStack:如何在写入响应之前捕获错误

时间:2012-07-24 08:38:26

标签: asp.net-mvc-3 exception-handling servicestack

我使用ServiceStack开发Rest服务。 我的模型包含一个DateTime属性,问题从它开始。如果客户端发布错误的格式化日期值作为字符串,ServiceStack将触发一个异常“字符串未被识别为有效的DateTime。”

Stack Trace: 


[FormatException: String was not recognized as a valid DateTime.]
   System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) +6364458
   ServiceStack.Text.Common.DeserializeBuiltin`1.<GetParseFn>b__b(String value) in C:\src\ServiceStack.Text\src\ServiceStack.Text\Common\DeserializeBuiltin.cs:58
   ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:79

[SerializationException: KeyValueDataContractDeserializer: Error converting to type: String was not recognized as a valid DateTime.]
   ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:95
   ServiceStack.ServiceHost.RestPath.CreateRequest(String pathInfo, Dictionary`2 queryStringAndFormData, Object fromInstance) in C:\src\ServiceStack\src\ServiceStack\ServiceHost\RestPath.cs:319
   ServiceStack.WebHost.Endpoints.RestHandler.GetRequest(IHttpRequest httpReq, IRestPath restPath) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:104
   ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:80
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +625
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270

我知道这是一个错误,我知道它必须是捕获但我想用我的错误代码和错误描述(人性化)来实现它。

任何建议对于如何在写入响应之前捕获异常(DebeugMode = true)或者服务向客户端发出异常都非常有帮助。

日Thnx

1 个答案:

答案 0 :(得分:3)

添加自定义请求活页夹(或更高级的选项是在您的DTO上实现IRequiresRequestStream)以绕过ServiceStack的反序列化。

有关此内容的更多信息包含在ServiceStack's wiki documentation