package com.bcxin.identify.config.exception;

import com.bcxin.identify.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
@Slf4j
public class ExceptionInterceptor {

	@ExceptionHandler(Exception.class)
	public Result handlerException(Exception ex, HttpServletRequest request) {
		if(ex instanceof BusinessException){
			BusinessException be = (BusinessException) ex;
			log.warn("本次业务异常编码：" + be.getCode() + "，业务异常消息："+ be.getMsg(),be);
			return Result.fail(request, be.getMsg(), null);
		}
		String exception = toString(ex);
		if (exception.length()>3000) {
			exception = exception.substring(0,3000);
		}
		log.error("全局异常捕获>>>>>>>>>>>>",ex);
		return Result.fail(request, ex.getMessage(), null);
	}

	private static String toString(Throwable e){
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		e.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}

}
