springboot3项目的搭建三(统一返回,异常,MVC配置跨域静态资源放行配置等)

springboot3项目的搭建三(统一返回异常等)

 一、统一返回 (其实两部分,一个是返回错误码可枚举可类,另一个是返回的实体其中data是泛型)

1.返回码:

package com.qiqi.common.constants;

public enum ReturnCode {

    SUCCESS(200, "操作成功"),
    NEED_LOGIN(401, "需要登录后操作"),
    NO_OPERATOR_AUTH(403, "无权限操作"),
    TOKEN_ILL(404,"token非法"),
    SYSTEM_ERROR(500, "出现错误"),
    USERNAME_EXIST(501, "用户名已经存在"),
    PHOMENUMBER_EXIST(502, "手机号已存在"),
    EMAIL_EXIST(503, "邮箱已存在"),
    REQUEST_USERNAME(504, "必须填写用户名"),
    LOGIN_ERROR(505, "用户名或密码错误");

    // 自定义状态码
    private final int code;

    // 自定义描述
    private final String msg;

    ReturnCode(int code, String errorMessage) {
        this.code = code;
        this.msg = errorMessage;
    }

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

}

2.返回实体

package com.qiqi.common.response;

import com.qiqi.common.constants.ReturnCode;
import lombok.Data;

import java.util.Objects;

@Data
public class ResultData<T> {
    /**
     * 响应编码
     */
    private Integer code;
    /**
     * 响应信息
     */
    private String msg;
    /**
     * 响应数据
     */
    private T data;
    /**
     * 接口请求时间
     */
    private long timestamp ;

    public ResultData(){
        this.timestamp = System.currentTimeMillis();
    }

    public ResultData(Integer code, String msg){
        this.code=code;
        this.msg=msg;
    }

    public ResultData(Integer code, String msg, T data){
        this.code=code;
        this.msg=msg;
        this.data=data;
    }

    public static ResultData success(){
        return ResultData.success(ReturnCode.SUCCESS.getCode(),ReturnCode.SUCCESS.getMsg());
    }
    public static ResultData success(int code, String msg){
        ResultData<Object> resultData = new ResultData<>();
        resultData.setCode(code);
        resultData.setMsg(msg);
        return resultData;
    }

    public static ResultData success(Object data){
        ResultData<Object> resultData = new ResultData<>(ReturnCode.SUCCESS.getCode(),ReturnCode.SUCCESS.getMsg());
        if (Objects.nonNull(data)){
            resultData.setData(data);
        }
        return resultData;
    }

    public static ResultData error(int code, String msg){
        ResultData<Object> resultData = new ResultData<>(code,msg);
        return resultData;
    }

    public static ResultData error(ReturnCode returnCode){
        ResultData<Object> resultData = new ResultData<>(returnCode.getCode(), returnCode.getMsg());
        return resultData;
    }
}

3. 使用

        //return ResultData.success(admins); //返回实体
        return ResultData.error(ReturnCode.EMAIL_EXIST);//返回 邮箱已存在

 

 

二、异常处理

现在最主要的是:使用@ControllerAdvice@ExceptionHandler注解来实现全局异常处理。

 https://www.cnblogs.com/fps2tao/p/16979358.html

 https://www.cnblogs.com/fps2tao/p/16982700.html

package com.qiqi.common.exception;

import com.qiqi.common.constants.ReturnCode;
import com.qiqi.common.response.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(value = {ArrayIndexOutOfBoundsException.class})
    public String arrayIndexOutOfBoundsException(Model model, Exception e){
        model.addAttribute("msg",e.getMessage());
        log.info(e.getMessage());
        return "error";
    }

    @ExceptionHandler(value = {NullPointerException.class})
    public String nullPointerException(Model model,Exception e){
        model.addAttribute("msg",e.getMessage());
        log.info(e.getMessage());
        return "error2";
    }


    @ExceptionHandler(value = {ArithmeticException.class})
    public ResultData<?> arithmeticException(Exception e){
        log.info(e.getMessage());
        return ResultData.error(ReturnCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {BizException.class})
    public ResultData<?> bizException(Exception e){
        log.info(e.getMessage());
        return ResultData.error(ReturnCode.BIX_ERROR.getCode(), e.getMessage());
    }


    @ExceptionHandler(value = {Exception.class})
    public ResultData<?> exception(Exception e){
        log.info(e.getMessage());
        return ResultData.error(ReturnCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }


}

 

 

 

三、MVC配置(跨域请求,项目首页配置,拦截器静态资源的放行)

package com.qiqi.framework.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;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    //设置首页
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/index/index");
    }


    /**
     * 拦截器配置:静态文件访问地址
     *
     * 一般我们在访问A(虚拟的)的时候,需要到B(实际的)的位置去访问。那么我们就需要用到addResourceHandlers
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //这里是指在url上面打的内容
        registry.addResourceHandler("/**")
                //下面的是指可以对应resources文件下那些内容
                .addResourceLocations("classpath:/")
                .addResourceLocations("classpath:/templates/")
                .addResourceLocations("classpath:/static/**");
        //绝对路径
        //registry.addResourceHandler("/file/**").addResourceLocations("file:/static/");
        //类路径
        //registry.addResourceHandler("/html/**").addResourceLocations("classpath:/static/");
    }


    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径,拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }


}

 

 

参考-异常:https://docs.spring.io/spring-boot/docs/3.2.3/reference/htmlsingle/#web.servlet.spring-mvc.error-handling

 

posted @ 2024-05-30 09:30  与f  阅读(34)  评论(0编辑  收藏  举报