全局处理异常

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 全局处理异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String globalExceptionCatchHandler(HttpServletRequest request,Exception e){
        logger.error("出现全局异常了"+e.getMessage(),e.fillInStackTrace());
        e.printStackTrace();
        //TODO 记录日志
        String method = request.getMethod();
        String contextPath = request.getContextPath();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String parameterJson = JSON.toJSONString(parameterMap);
        logger.error("time:"+System.currentTimeMillis());
        logger.error("method:"+method);
        logger.error("contextPath:"+contextPath);
        logger.error("parameterJson:"+parameterJson);


        Map<String,Object> map = Maps.newHashMap();
        map.put("code","e");
        map.put("msg","请求异常,请联系....");
        return JSON.toJSONString(map);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37367413/article/details/80570718