Springboot 拦截抛出异常并全局处理该异常

代码片段

  • 拦截器
  • 注册拦截器,使其生效
  • 全局异常处理

拦截器

import com.hong.manager.common.exception.LicenseException;
import com.hong.manager.system.service.LicenseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LicenseInterceptor extends HandlerInterceptorAdapter {

    private final LicenseService licenseService;

    public LicenseInterceptor(LicenseService licenseService) {
        this.licenseService = licenseService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("进入 license 拦截校验");
        }
        if (!licenseService.valid()) {
            log.info("license 已过期");
            throw new LicenseException("License 已过期");
            // return false;
        }
        log.debug("license 校验通过");

        return super.preHandle(request, response, handler);
    }
}

注册拦截器,使其生效

package com.hong.manager.framework.config;

import com.hong.manager.common.config.Global;
import com.hong.manager.common.constant.Constants;
import com.hong.manager.framework.interceptor.LicenseInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    /**
     * 首页地址
     */
    @Value("${shiro.user.indexUrl}")
    private String indexUrl;

    @Autowired
    private LicenseInterceptor licenseInterceptor;

    /**
     * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:" + indexUrl);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 本地文件上传路径 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/");

        /** swagger配置 */
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludeLicense = new ArrayList<>();
        excludeLicense.add("/license/**");
        excludeLicense.add("/login");
        excludeLicense.add("/logout");// 用户初始化等接口

        // /captcha/captchaImage?type=math
        String[] commonUrl = {"/index", "/index.html", "/", "/**/*.css",
                "/**/*.js", "/**/*.png", "/**/*.jpg", "/captcha/**", "/img/**", "/**/*.svg",
                "/**/*.jpeg", "/**/*.gif", "/**/fonts/*"};
        Collections.addAll(excludeLicense, commonUrl);

        // 再登录拦截之后拦截,防止登录拦截中的非拦截的接口,被license拦截
        // 滤过license更新和校验两个接口
        registry.addInterceptor(licenseInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludeLicense);
    }
}

全局异常处理

import com.hong.manager.common.core.domain.AjaxResult;
import com.hong.manager.common.exception.BusinessException;
import com.hong.manager.common.exception.LicenseException;
import com.hong.manager.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * License失效异常
     */
    @ExceptionHandler(LicenseException.class)
    public Object licenseException(HttpServletRequest request, BusinessException e) {
        log.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request)) {
            return AjaxResult.error(e.getMessage());
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("errorMessage", e.getMessage());
            modelAndView.setViewName("license/expire");
            return modelAndView;
        }
    }
}

你可能感兴趣的:(Java,spring,boot,java,servlet)