package com.mybb.common.exception; import com.mybb.common.base.entity.Result; import com.mybb.common.enums.EnumCode; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; /** * TODO * * @author liu pei * @version 1.0 * @email 3268727800@qq.com * @date 2020/12/23 11:05 */ @RestControllerAdvice public class GlobalExceptionHandler { protected static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理自定义异常 * @param e * @return */ @ExceptionHandler(BusinessException.class) public Result handleRRException(BusinessException e) { log.error("返回错误:msg={}, e={}", e.getMessage(), ExceptionUtils.getStackTrace(e)); return Result.error(e.getCode(),e.getMessage()); } /** * 方法参数校验(不能为空,长度限制,格式不正确等等) */ @ExceptionHandler(MethodArgumentNotValidException.class) public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error("返回错误:msg={}, e={}", e.getMessage(),ExceptionUtils.getStackTrace(e)); return Result.error(EnumCode.ERROR_BUSY.getCode(),e.getBindingResult().getFieldError().getDefaultMessage()); } /** * ValidationException */ @ExceptionHandler(ValidationException.class) public Result handleValidationException(ValidationException e) { log.error("返回错误:msg={}, e={}", e.getMessage(),ExceptionUtils.getStackTrace(e)); return Result.error(EnumCode.DATA_ERROR.getCode(),e.getCause().getMessage()); } /** * ConstraintViolationException */ @ExceptionHandler(ConstraintViolationException.class) public Result handleConstraintViolationException(ConstraintViolationException e) { log.error("返回错误:msg={}, e={}", e.getMessage(),ExceptionUtils.getStackTrace(e)); return Result.error(EnumCode.DATA_ERROR.getCode(),EnumCode.DATA_ERROR.getDesc()); } /** * 系统路径不存在异常信息捕获 * @param e * @return */ @ExceptionHandler(NoHandlerFoundException.class) public Result handlerNoFoundException(Exception e) { log.error("返回错误:msg={}, e={}", e.getMessage(),ExceptionUtils.getStackTrace(e)); return Result.error(EnumCode.ERROR.getCode(),EnumCode.ERROR.getDesc()); } /** * 系统异常捕获处理 * @param e * @return */ @ExceptionHandler(Exception.class) public Result handleException(Exception e) { log.error("返回错误:msg={}, e={}", e.getMessage(),ExceptionUtils.getStackTrace(e)); return Result.error(EnumCode.ERROR.getCode(),EnumCode.ERROR.getDesc()); } }