ServiceStack将ResponseStatus中的错误映射到没有验证器的自定义错误

时间:2015-08-10 22:16:27

标签: servicestack

Servicestack中是否有一种方法可以将自定义请求验证错误映射到resposeStatus对象中的errors字段而不使用Validators。

即。如果我有一个

的自定义错误列表
{
    "ErrorCode": "NotEmpty",
    "FieldName": "Company",
    "Message": "'Company' should not be empty."
}

如何使用out Validators映射到ResponseStatus对象。

1 个答案:

答案 0 :(得分:1)

ServiceStack异常只是具有填充的ResponseStatus的响应DTO,其中返回了HTTP错误代码。您可以通过多种方式自定义错误响应,包括:

使用填充的Response DTO

返回HttpError

如果要发送自定义的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,
}; 

覆盖AppHost中的OnExceptionTypeFilter

默认情况下,当您抛出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
                }
            }
        }
    }    
}