package com.ycl.jxkg.config.spring.exception; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ycl.jxkg.base.Result; import com.ycl.jxkg.base.SystemCode; import com.ycl.jxkg.utils.ErrorUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; /** * @version 3.5.0 * @description: The type Exception handle. * Copyright (C), 2020-2024, 武汉思维跳跃科技有限公司 * @date 2021/12/25 9:45 */ @RestControllerAdvice public class ExceptionHandle { private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); /** * 公司项目的包结构,用于缩短错误日志的长度 */ private final static String COMPANY_PACKAGE = "com.ycl.jxkg."; /** * Handler rest response. * * @param e the e * @return the rest response */ @ExceptionHandler(Exception.class) @ResponseBody public Result handler(Exception e, HttpServletRequest request) { String errMsg = String.format("系统异常-%s", e.getMessage()); this.printExceptionLocation(e, request, errMsg); return new Result<>(SystemCode.InnerError.getCode(), SystemCode.InnerError.getMessage()); } /** * Handler rest response. * * @param e the e * @return the rest response */ @ExceptionHandler(RuntimeException.class) @ResponseBody public Result handler(RuntimeException e, HttpServletRequest request) { String errMsg = String.format("系统异常-%s", e.getMessage()); this.printExceptionLocation(e, request, errMsg); return new Result<>(SystemCode.InnerError.getCode(), e.getMessage()); } /** * JSON传参数据校验异常 * * @param e * @param request * @return * @throws JsonProcessingException */ @ExceptionHandler(MethodArgumentNotValidException.class) public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) throws JsonProcessingException { List err = e.getBindingResult().getAllErrors().stream().map(error -> error.getDefaultMessage()).collect(Collectors.toList()); String s = new ObjectMapper().writeValueAsString(err); String errMsg = String.format("参数校验失败-%s", s); this.printExceptionLocation(e, request, errMsg); return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), s); } /** * Handler rest response. * * @param e the e * @return the rest response */ @ExceptionHandler(BindException.class) @ResponseBody public Result handler(BindException e) { String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> { FieldError fieldError = (FieldError) file; return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage()); }).collect(Collectors.joining()); return new Result<>(SystemCode.ParameterValidError.getCode(), errorMsg); } /** * 请求方式不支持异常 * * @param e * @param request * @return */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) { String errMSg = String.format("不支持%s请求", e.getMethod()); this.printExceptionLocation(e, request, errMSg); return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } /** * 打印异常出现位置 * * @param e */ private void printExceptionLocation(Throwable e, HttpServletRequest request, String errMsg) { StackTraceElement stackTraceElement = e.getStackTrace()[0]; String className = stackTraceElement.getClassName().contains(COMPANY_PACKAGE) ? stackTraceElement.getClassName().split(COMPANY_PACKAGE)[1] : stackTraceElement.getClassName(); logger.error("接口:【{}】, 异常类:【{}】,方法:【{}】,所在行:【{}】, 错误信息:【{}】", request.getRequestURI(), className, stackTraceElement.getMethodName(), stackTraceElement.getLineNumber(), errMsg); } }