package com.bcxin.signature.config.exception;

import com.bcxin.signature.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@Slf4j
@RestControllerAdvice
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);
	}*/

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
														  HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
		return Result.fail(e.getMessage());
	}

	/** * 拦截未知的运行时异常 */
	@ExceptionHandler(RuntimeException.class)
	public Result handleRuntimeException(RuntimeException e, HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生未知异常.", requestURI, e);
		return Result.fail(e.getMessage());
	}
	/** * 系统异常 */
	@ExceptionHandler(Exception.class)
	public Result handleException(Exception e, HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生系统异常.", requestURI, e);
		return Result.fail(e.getMessage());
	}

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

}
