package com.whyc.aop; import com.whyc.constant.OperationLogEnum; import com.whyc.dto.Response; import com.whyc.service.OperationLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 针对RestController层捕捉异常,结果统一返回 */ @RestControllerAdvice(annotations = {RestController.class, Controller.class, Service.class}) public class CustomExceptionResultHandler { @Autowired private OperationLogService logService; /**错误捕捉,状态码:202*/ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.ACCEPTED) public Response sendErrorResponse2Defined(Exception e, HttpServletResponse response, HttpServletRequest request){ String exceptionStr = e.toString(); String requestURI = request.getRequestURI(); //单项提取-登录超时 Integer type = OperationLogEnum.TYPE_1_SYS.getType(); if (exceptionStr.contains("login") && exceptionStr.contains("imeout")) { logService.record(OperationLogEnum.TYPE_1_SYS.getType(),OperationLogEnum.TYPE_2_CONNECTION_TIMEOUT.getType(), "登录请求超时", "异常信息:" + exceptionStr); } else { logService.record(OperationLogEnum.TYPE_1_SYS.getType(),OperationLogEnum.TYPE_2_EXCEPTION.getType(),"接口调用异常", "接口调用异常:调用接口" + requestURI + "发生错误:" + exceptionStr); } return new Response().set(0, "接口请求异常,请联系软件人员进行处理.异常信息" + exceptionStr); } }