我们在Spring中有一个RestFul webservice,为了验证我们使用Spring验证器的请求参数 以下是我的验证器的外观:
@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?
}
}
在我的Exception处理程序类中,我收到验证错误并生成我的自定义异常:
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;
}
我的问题是: 如何只从Validator类发送错误代码而不是文件名。另外如何修改我的异常处理程序方法来处理以下2个场景:
发送字段名称和错误代码时
仅发送错误代码且未归档姓名。
答案 0 :(得分: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;
}