spring boot restful api 方法参数 BindException 异常处理

 

客户端 post json 数据,api 方法 接收的参数绑定出现异常,抛出  BindException 异常,可以按照如下的方式处理

1、方法参数中增加 BindingResult 参数,通过 bindingResult.hasErrors()  判断是否出错

2、在 配置类中重写 addFormatters 方法

@Configuration

public class MyWebAppConfigurer extends WebMvcConfigurerAdapter


@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

	@Value("${home.page}")
	private String homePage;

	@Value("${spring.profiles.active}")
	private String env;

	@Bean
	public HttpMessageConverter responseBodyConverter() {
		return new StringHttpMessageConverter(Charset.forName("UTF-8"));
	}
	
   @Override
    public void addFormatters(FormatterRegistry registry) {
	   	registry.addConverter(new StringtoDateConverter());
        super.addFormatters(registry);
    }

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("/index.html");
		registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
		super.addViewControllers(registry);
	}


	@Override
	public void configureMessageConverters(List> converters) {

		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		FastJsonConfig config = new FastJsonConfig();
		config.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.SkipTransientField, 
				SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteNullNumberAsZero);
		converter.setFastJsonConfig(config);
		converter.setDefaultCharset(Charset.forName("UTF-8"));
		
		super.configureMessageConverters(converters);
		converters.add(converter);
		converters.add(responseBodyConverter());

	}

	@Override
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.favorPathExtension(false);
		super.configureContentNegotiation(configurer);
	}

	@Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
		configurer.setUseSuffixPatternMatch(true).setUseTrailingSlashMatch(true);
	}


	@Override
	public void configureHandlerExceptionResolvers(List exceptionResolvers) {
		exceptionResolvers.add(new MyHandlerExceptionResolver());
	}


	
}

 

定义 StringtoDateConverter 类继承 org.springframework.core.convert.converter.Converter 接口


@Component
public class StringToDateConverter implements Converter {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public Date convert(String source) {
		if (StringUtils.isNotEmpty(source)) {
			try {
				if(source.matches("^\\d{4}-\\d{2}-\\d{2}[^\\r\\t]*")) {
					return DateUtil.parse(source);
				} else if(source.matches("^\\d+")) {
					Date d = new Date();
					d.setTime(Long.valueOf(source));
					return d;
				} else {
					logger.warn("日期参数错误:\"{}\"", source);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}

 

目前按照 2 处理,这样我就不用一个个方法来加参数 BindingResult 参数

 

你可能感兴趣的:(java)