yml文件配置
spring:
resources:
add-mappings: false # 不要为我们工程中的资源文件建立映射
mvc:
throw-exception-if-no-handler-found: true # 出现错误时, 直接抛出异常
异常拦截处理
import com.qing.music.config.CommonFinal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
/**
* 异常处理
*/
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常,也可以指定其他异常
public Object handler(Exception exception,HttpServletRequest request){
// log.info("进入异常 处理中 ----------------------------------------");
//去掉统一拦截打的标签,避免进入统一处理返回值方法
request.removeAttribute(CommonFinal.RESPONSE_RESULT_ANN);
//记录异常信息
StackTraceElement stackTraceElement=exception.getStackTrace()[0];
log.error("------------------异常信息:{}",exception.getLocalizedMessage());
log.error("------------------异常信息所在类名:{}",stackTraceElement.getClassName());
log.error("------------------异常信息所在方法名:{}",stackTraceElement.getMethodName());
log.error("------------------异常信息所在行:{}",stackTraceElement.getLineNumber());
log.error("------------------异常信息:{}",exception.getMessage());
if (exception instanceof CommonException){ //自定义异常
CommonException customException = (CommonException) exception;
return Result.failure(customException.getCommonEnum().getCode(),customException.getCommonEnum().getMessage(),exception.getMessage());
} else if (exception instanceof NoHandlerFoundException) { //404异常处理
return Result.failure(ResultCode.PAGE_NOT_FOUND);
} else { //500异常
return Result.failure(ResultCode.UNKNOWN_EXCEPTION);
}
}
}
网友评论