springboot项目通用配置之(全局异常处理,跨域请求配置)

 全局异常处理

package com.sf.gis.boot.rcboot.config;

import com.sf.gis.boot.rcboot.util.JsonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 80004819
 * @ClassName:
 * @Description:
 * @date 2020年09月12日 14:59:40
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public JsonResponse globalException(HttpServletResponse response, Exception ex) {
        return JsonResponse.error(ex.getMessage());
    }

}



 跨域请求配置

package com.sf.gis.boot.rcboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author 80004819
 * @ClassName:
 * @Description:
 * @date 2020年09月11日 10:35:37
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

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

猜你喜欢

转载自blog.csdn.net/qq_31905135/article/details/108702646