我们在 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;
}
我的问题是:我怎样才能从验证器类中只发送错误代码而不是归档名称。另外如何修改我的异常处理程序方法来处理以下两种情况:
发送字段名称和错误代码时
当仅发送错误代码而不发送名称时。