0

我们在 Spring 中有一个 RestFul Web 服务,为了验证请求参数,我们使用 Spring 验证器 I以下是我的验证器的外观:

 @Override
public void validate( Object oObject, Errors oErrors ) 
{

    RequestDAO oRequest = (RequestDAO) oObject;

    if (Validation on FIELD 1 fails  ) 
    {
       oErrors.rejectValue( "FIELD1", ERROR CODE );
    } 
  else if ( If any other validation fails ) 
 {
        oErrors.rejectValue( "", A Different error code );
        //I just want to send the ERROR CODE here and not the name of the filed
        //IS it the correct way to do it?
    }

}

在我的异常处理程序类中,我收到验证错误并生成我的自定义异常:

  protected AppException convertValidionErrorToCustomException(    MethodArgumentNotValidException oMethodArgNotvalidExp ) {

    CustomException oAppExp = null;

    BindingResult oBindingResult = oMethodArgNotvalidExp.getBindingResult();
    // Get the first error associated with a field, if any.
    FieldError oFieldError = oBindingResult.getFieldError();
    // IF I DONT SENT THE NAME OF THE FIELD I GET NULL ABOVE and thus an NP exp
    String sCode = oFieldError.getCode();
    if ( StringUtils.isEmpty( sCode ) || !StringUtils.isNumeric( sCode ) )
  {

        oAppExp = new CustomException( oMethodArgNotvalidExp );

    } 
  else 
  {

        int iErrorCode = Integer.parseInt( oFieldError.getCode() );
        String sFieldName = oFieldError.getField();
        if ( !StringUtils.isEmpty( sFieldName ) ) {

            oAppExp = new CustomException( iErrorCode, sFieldName );

        } else {

            oAppExp = new CustomException( iErrorCode );
        }
    }

    return oAppExp;
}

我的问题是:我怎样才能从验证器类中只发送错误代码而不是归档名称。另外如何修改我的异常处理程序方法来处理以下两种情况:

  • 发送字段名称和错误代码时

  • 当仅发送错误代码而不发送名称时。

4

1 回答 1

0

我终于找到了办法。我更新了我的异常处理程序有这个:

   protected CustomException convertValidionErrorToAppException( MethodArgumentNotValidException oMethodArgNotvalidExp ) {

    CustomException Exp = null;

    BindingResult oBindingResult = oMethodArgNotvalidExp.getBindingResult();
    // Get the first error associated with a field, if any.\
    if ( oBindingResult.hasFieldErrors() ) {
        Exp = processFieldError( oBindingResult, oMethodArgNotvalidExp );

    } else {
        Exp = processErrors( oBindingResult, oMethodArgNotvalidExp );
    }

    return Exp;
}

processFieldError(oBindingResult, oMethodArgNotvalidExp); 方法处理所有字段错误,而 processErrors(oBindingResult, oMethodArgNotvalidExp) 将处理非字段错误。该方法看起来像这样

   protected CustomExceptionprocessErrors( BindingResult oBindingResult,     MethodArgumentNotValidException oMethodArgNotvalidExp ) {
    CustomException Exp = null;
    //Get all errors from Binding Errors
    ObjectError oError = oBindingResult.getAllErrors().get( 0 );
    String sCode = oError.getCode();
    if ( StringUtils.isEmpty( sCode ) || !StringUtils.isNumeric( sCode ) ) {

        Exp = new CustomException( oMethodArgNotvalidExp );

    } else {
        int iErrorCode = Integer.parseInt( sCode );
        Exp = new CustomException( iErrorCode );
    }
    return Exp;
}
于 2015-06-03T03:20:31.797 回答