Servicestack中是否有一种方法可以将自定义请求验证错误映射到resposeStatus对象中的errors字段而不使用Validators。
即。如果我有一个
的自定义错误列表{
"ErrorCode": "NotEmpty",
"FieldName": "Company",
"Message": "'Company' should not be empty."
}
如何使用out Validators映射到ResponseStatus对象。
答案 0 :(得分:1)
ServiceStack异常只是具有填充的ResponseStatus
的响应DTO,其中返回了HTTP错误代码。您可以通过多种方式自定义错误响应,包括:
如果要发送自定义的ResponseStatus DTO,可以抛出HttpError,例如:
var responseDto = new ErrorResponse {
ResponseStatus = new ResponseStatus {
ErrorCode = typeof(ArgumentException).Name,
Message = "Invalid Request",
Errors = new List<ResponseError> {
new ResponseError {
ErrorCode = "NotEmpty",
FieldName = "Company",
Message = "'Company' should not be empty."
}
}
}
};
throw new HttpError(HttpStatusCode.BadRequest, "ArgumentException") {
Response = responseDto,
};
默认情况下,当您抛出ArgumentException
内置OnExceptionTypeFilter
时,会自动为指定的ParamName添加一个填充的ResponseError
,例如:
public virtual void OnExceptionTypeFilter(
Exception ex, ResponseStatus responseStatus)
{
var argEx = ex as ArgumentException;
var isValidationSummaryEx = argEx is ValidationException;
if (argEx != null && !isValidationSummaryEx && argEx.ParamName != null)
{
var paramMsgIndex = argEx.Message.LastIndexOf("Parameter name:");
var errorMsg = paramMsgIndex > 0
? argEx.Message.Substring(0, paramMsgIndex)
: argEx.Message;
responseStatus.Errors.Add(new ResponseError
{
ErrorCode = ex.GetType().Name,
FieldName = argEx.ParamName,
Message = errorMsg,
});
}
}
您也可以在AppHost中覆盖此方法,以自定义您自己的异常的ResponseStatus。
IResponseStatusConvertible
在幕后,ValidationException
允许自定义响应DTO的方式是having ValidationException implement IResponseStatusConvertible接口。
E.g。以下是如何创建自定义异常,在响应DTO中抛出填充的字段错误:
public class CustomFieldException : Exception, IResponseStatusConvertible
{
...
public string FieldErrorCode { get; set; }
public string FieldName { get; set; }
public string FieldMessage { get; set; }
public ResponseStatus ToResponseStatus()
{
return new ResponseStatus {
ErrorCode = GetType().Name,
Message = Message,
Errors = new List<ResponseError> {
new ResponseError {
ErrorCode = FieldErrorCode,
FieldName = FieldName,
Message = FieldMessage
}
}
}
}
}