package com.shanghaichengdi.ghjgitem.config;

import com.shanghaichengdi.ghjgitem.constant.HttpStatus;
import com.shanghaichengdi.ghjgitem.exception.EnumException;
import com.shanghaichengdi.ghjgitem.vo.response.ReturnMsg;
import com.shanghaichengdi.ghjgitem.exception.AesDecodeException;
import com.shanghaichengdi.ghjgitem.util.PrintLogUtils;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(EnumException.class)
  public ReturnMsg NullPointerExceptionHandler(HttpServletRequest request, EnumException e) {
    commonExceptionPrint(request, e);
    return ReturnMsg.error(HttpStatus.ERROR, e.getMessage());
  }

  @ExceptionHandler(NullPointerException.class)
  public ReturnMsg NullPointerExceptionHandler(HttpServletRequest request, NullPointerException e) {
    commonExceptionPrint(request, e);
    return ReturnMsg.error(HttpStatus.ERROR, "传入参数不符合规范要求");
  }

  @ExceptionHandler(AesDecodeException.class)
  public ReturnMsg AesDecodeExceptionHandler(HttpServletRequest request, AesDecodeException e) {
    log.error("url:{}请求异常", request.getRequestURI());
    return ReturnMsg.error(HttpStatus.FORMATTER_ERROR, e.getMessage());
  }

  /********************************
   *  @function  : 空指针异常捕捉
   *  @parameter : [e：Exception | 异常]
   *  @date      : 2023/12/5 11:47
   ********************************/
  @ExceptionHandler(value = Exception.class)
  public ReturnMsg exceptionHandler(HttpServletRequest request, Exception e) {
    commonExceptionPrint(request, e);
    return ReturnMsg.error(HttpStatus.ERROR, "服务器内部异常异常");
  }

  private void commonExceptionPrint(HttpServletRequest request, Exception e) {
    log.error("服务器内部异常异常，url：{}, 异常内容：{}", request.getRequestURI(), e.getMessage());
    PrintLogUtils.printErrorLogInfo(e);
  }
}

