swagger和自定义异常都中文乱码

springboot使用swagger2中文乱码,自定义异常的中文也乱码。
部分代码:

@Configuration
@EnableSwagger2
//@Component
public class SwaggerConfig implements WebMvcConfigurer
{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();
        // 生成JSON时,将所有Long转换成String
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        // 时间格式化
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 设置格式化内容
        converter.setObjectMapper(objectMapper);
        converters.add(0, converter);
    }
    @Bean
 public Docket webApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)
         .groupName("webApi")
         .apiInfo(webApiInfo())
         .select()
         .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
         .paths(Predicates.not(PathSelectors.regex("/error.*")))
         .build();
       }
    private ApiInfo webApiInfo(){

         return new ApiInfoBuilder()
         .title("仓库管理系统")
         .description("本文档描述了仓库管理系统接口定义")
         .version("1.0")
        .contact(new Contact("Helen", "http://atguigu.com",
                "55317332@qq.com"))
         .build();
         }
 }

自定义异常

@Data
@AllArgsConstructor
@NoArgsConstructor
public class WNNException extends RuntimeException{
    private Integer code;//异常状态码
    private String msg;//异常信息
    private boolean status;
}

配置类中配置异常类

//配置
@ExceptionHandler(WNNException.class)
    public R error(WNNException e) {
        e.printStackTrace();
    return R.ok().message(new String(e.getMsg())).code(e.getCode()).success(e.isStatus());
    }

img

img

设置一下idea的编码格式 设置成UTF-8

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7676668
  • 这篇博客也不错, 你可以看下SpringBoot 使用 swagger2 构建在线接口文档
  • 除此之外, 这篇博客: 关于 springBoot 使用 swagger2生成接口文档 的正确姿势中的 二、创建一个配置文件 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 	/**
    	*通过springfox 提供的Docket 对象,我们可以灵活的配置 Swagger 的各项属性。
    	*/
    	@Configuration
    	@EnableSwagger2 //@EnableSwagger2 是启用 Swagger2
    	public class Swagger2Config {
    
        @Bean
        public Docket createRestAPi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()//初始化并返回一个API选择构造器
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))//添加路径选择条件扫描接口-> basePackage(final String basePackage):返回一个断言(Predicate),该断言包含所有匹配basePackage下所有类的请求路径的请求处理器;	any():返回包含所有满足条件的请求处理器的断言,该断言总为true;	none():返回不满足条件的请求处理器的断言,该断言总为false
                    .paths(PathSelectors.any())//设置路径筛选 -> any():满足条件的路径,该断言总为true;	none():不满足条件的路径,该断言总为false;	regex(final String pathRegex):符合正则的路径
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("测试 APIS")
                    .description("了解更多请联系:")
                    .termsOfServiceUrl("http://www.xxxx.com")
                    .contact("180xxxx9005")
                    .version("1.0")
                    .build();
        }
    
    }
    
  • 您还可以看一下 刘磊老师的SpringBoot2.0实战教程课程中的 Swagger简单介绍小节, 巩固相关知识点