springboot捕获所有的Error异常并处理


import com.test.bean.mongo.ErrorLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@ControllerAdvice(basePackages = {"com.test"})
public class ExceptionService {

        @Autowired
        private MongoTemplate mongoTemplate;
        private static final Logger logger = LoggerFactory.getLogger(ExceptionService.class);
        @ExceptionHandler(Exception.class)
        public void UserExceptionHandler(HttpServletRequest request, Exception e){
            //error日志统一处理
            //String error = getExceptionInfo(e);//此方法使用io效率比较低,不推荐使用
            String error = getMsg(e);//推荐使用该方法
            logger.error(error);
            //异步处理
            new Thread(() -> {
                //逻辑代码
                String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

                ErrorLog errorLog = new ErrorLog();
                errorLog.setUrl(request.getRequestURI());
                errorLog.setDetails(error);
                errorLog.setDate(sdf.format(new Date()));
                mongoTemplate.insert(errorLog);

            }).start();
        }
        private static String getExceptionInfo(Exception ex) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PrintStream printStream = new PrintStream(out);
            ex.printStackTrace(printStream);
            String string = new String(out.toByteArray());
            try {
                printStream.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return string;
        }
        private static String getMsg(Exception e) {
            StackTraceElement[] stackTrace = e.getStackTrace();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(e.toString()).append("\r\n");
            for (StackTraceElement stackTraceElement : stackTrace) {
                stringBuffer.append("\tat ").append(stackTraceElement.getClassName()).append(".")
                        .append(stackTraceElement.getMethodName())
                        .append("(").append(stackTraceElement.getFileName()).append(":").append(stackTraceElement.getLineNumber())
                        .append(")\r\n");
            }
            return stringBuffer.toString();
        }


}

你可能感兴趣的:(springboot,exception,springboot,mongodb)