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;
    }
}

  

相关文章:

  • 2021-07-03
  • 2021-11-19
  • 2021-11-03
  • 2021-08-09
  • 2022-02-06
  • 2021-06-15
  • 2021-11-08
  • 2021-08-14
猜你喜欢
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案