|
|
package com.manage.controller;
|
|
|
|
|
|
/**
|
|
|
* @ProjectName:
|
|
|
* @Description:
|
|
|
* @Param 传输参数
|
|
|
* @Return
|
|
|
* @Author: 曾文和
|
|
|
* @CreateDate: 2020/5/15 16:14
|
|
|
* @UpdateUser: 曾文和
|
|
|
* @UpdateDate: 2020/5/15 16:14
|
|
|
* @UpdateRemark: 更新说明
|
|
|
* @Version: 1.0
|
|
|
*/
|
|
|
|
|
|
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
|
|
|
import com.manage.util.ExceptionPrintUtil;
|
|
|
import org.apache.logging.log4j.LogManager;
|
|
|
import org.apache.logging.log4j.Logger;
|
|
|
import org.springframework.validation.BindException;
|
|
|
import org.springframework.validation.BindingResult;
|
|
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
import org.springframework.web.bind.annotation.ResponseBody;
|
|
|
import org.springframework.web.servlet.ModelAndView;
|
|
|
|
|
|
import java.util.HashMap;
|
|
|
import java.util.Map;
|
|
|
|
|
|
@ControllerAdvice
|
|
|
public class GlobalExceptionHandler {
|
|
|
private static Logger log = LogManager.getLogger("errorLog");
|
|
|
@ExceptionHandler(value = Exception.class)//指定拦截的异常
|
|
|
public ModelAndView errorHandler(Exception e) {
|
|
|
return returnMv(e, "服务器出错了,请联系系统管理员");
|
|
|
}
|
|
|
|
|
|
@ExceptionHandler(value = RuntimeException.class)//指定拦截的异常
|
|
|
public ModelAndView runtimeHandler(Exception e) {
|
|
|
return returnMv(e, "服务器出错了,请联系系统管理员");
|
|
|
}
|
|
|
|
|
|
@ExceptionHandler(BindException.class)
|
|
|
@ResponseBody
|
|
|
public Map<String, Object> bindErrHandler(BindException e) {
|
|
|
Map<String,Object> map = new HashMap<String, Object>(3) {{
|
|
|
put("code", "500");
|
|
|
put("msg", "参数有误");
|
|
|
BindingResult bindingResult = e.getBindingResult();
|
|
|
put("fieldErrors", new HashMap<String, String>(bindingResult.getErrorCount()) {{
|
|
|
bindingResult.getFieldErrors().forEach(fieldError -> put(fieldError.getField(), fieldError.getDefaultMessage()));
|
|
|
}});
|
|
|
}};
|
|
|
log.error(map.toString());
|
|
|
return map;
|
|
|
}
|
|
|
|
|
|
private ModelAndView returnMv(Exception e, String msg) {
|
|
|
ModelAndView mv = new ModelAndView();
|
|
|
/* 使用FastJson提供的FastJsonJsonView视图返回,不需要捕获异常 */
|
|
|
FastJsonJsonView view = new FastJsonJsonView();
|
|
|
Map<String, Object> attributes = new HashMap<>(1);
|
|
|
attributes.put("code", "500");
|
|
|
attributes.put("msg", msg);
|
|
|
view.setAttributesMap(attributes);
|
|
|
mv.setView(view);
|
|
|
//方法名
|
|
|
ExceptionPrintUtil.printException(e);
|
|
|
e.printStackTrace();
|
|
|
return mv;
|
|
|
}
|
|
|
}
|