全局异常处理(跨域)

全局异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 文件大小限制主力
    @ExceptionHandler(value = {MultipartException.class})
    @ResponseStatus(value = HttpStatus.OK)
    public AjaxResult handleMultipartException(MaxUploadSizeExceededException e) {
        String msg;
        if (e.getCause().getCause() instanceof FileSizeLimitExceededException) {
            log.error(e.getMessage());
            msg = "上传文件过大[单文件大小不得超过1M]";
        } else if (e.getCause().getCause() instanceof SizeLimitExceededException) {
            log.error(e.getMessage());
            msg = "上传文件过大[总上传文件大小不得超过10M]";
        } else {
            msg = "上传文件失败";
        }
        return AjaxResult.fail(msg);
    }
}

注意: 全局异常处理可能会出现跨域

解决跨域

@Configuration
public class ApplicationConfig implements WebMvcConfigurer, InitializingBean, DisposableBean {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("*")
            .allowedOrigins("*");
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*"); //允许任何域名
        corsConfiguration.addAllowedHeader("*"); //允许任何头
        corsConfiguration.addAllowedMethod("*"); //允许任何方法
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); //注册
        return new CorsFilter(source);
    }
}

你可能感兴趣的:(全局异常处理(跨域))