封装实体验证

import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
//如果返回的为json数据或其它对象,添加该注解
@ResponseBody
public class GlobalErrorHandler {
    //添加全局异常处理流程,根据需要设置需要处理的异常,本文以MethodArgumentNotValidException为例
    @ExceptionHandler(value=MethodArgumentNotValidException.class)
    public JSONObject MethodArgumentNotValidHandler(HttpServletRequest request,
                                                MethodArgumentNotValidException exception) throws Exception
    {
        JSONObject object = new JSONObject();
        StringBuffer stringBuffer = new StringBuffer();
        //解析原错误信息,封装后返回,此处返回非法的字段名称,原始值,错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            stringBuffer.append(error.getDefaultMessage());
            stringBuffer.append(",");
        }
        String str = "";
        if(stringBuffer.length()>0) {
            str = stringBuffer.substring(0, stringBuffer.length() - 1);
        }
        object.put("error_code",3);
        object.put("error_msg",str);

        return object;
    }
}

  

原文地址:https://www.cnblogs.com/liaoyanglong/p/10702156.html