76 lines
2.4 KiB
Java
76 lines
2.4 KiB
Java
package io.common.exception;
|
|
|
|
import cn.hutool.core.map.MapUtil;
|
|
import io.common.utils.HttpContextUtils;
|
|
import io.common.utils.IpUtils;
|
|
import io.common.utils.JsonUtils;
|
|
import io.common.utils.Result;
|
|
import io.modules.log.entity.SysLogErrorEntity;
|
|
import io.modules.log.service.SysLogErrorService;
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import lombok.AllArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.dao.DuplicateKeyException;
|
|
import org.springframework.http.HttpHeaders;
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* 异常处理器
|
|
*/
|
|
@Slf4j
|
|
@RestControllerAdvice
|
|
@AllArgsConstructor
|
|
public class RenExceptionHandler {
|
|
private final SysLogErrorService sysLogErrorService;
|
|
|
|
/**
|
|
* 处理自定义异常
|
|
*/
|
|
@ExceptionHandler(RenException.class)
|
|
public Result handleRenException(RenException ex) {
|
|
System.out.println("自定义捕捉异常!");
|
|
Result result = new Result();
|
|
result.error(500, ex.getMsg());
|
|
return result;
|
|
}
|
|
|
|
@ExceptionHandler(DuplicateKeyException.class)
|
|
public Result handleDuplicateKeyException(DuplicateKeyException ex) {
|
|
Result result = new Result();
|
|
result.error("数据库中已存在该记录!");
|
|
return result;
|
|
}
|
|
|
|
@ExceptionHandler(Exception.class)
|
|
public Result handleException(Exception ex) {
|
|
System.out.println("全局捕捉异常!");
|
|
log.error(ex.getMessage(), ex);
|
|
saveLog(ex);
|
|
return new Result().error(ex.getMessage());
|
|
}
|
|
|
|
/**
|
|
* 保存异常日志
|
|
*/
|
|
private void saveLog(Exception ex) {
|
|
SysLogErrorEntity log = new SysLogErrorEntity();
|
|
//请求相关信息
|
|
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
|
|
log.setIp(IpUtils.getIpAddr(request));
|
|
log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
|
|
log.setRequestUri(request.getRequestURI());
|
|
log.setRequestMethod(request.getMethod());
|
|
Map<String, String> params = HttpContextUtils.getParameterMap(request);
|
|
if (MapUtil.isNotEmpty(params)) {
|
|
log.setRequestParams(JsonUtils.toJsonString(params));
|
|
}
|
|
//异常信息
|
|
log.setErrorInfo(ExceptionUtils.getErrorStackTrace(ex));
|
|
//保存
|
|
sysLogErrorService.save(log);
|
|
}
|
|
}
|