springboot返回,修改http状态码

本文介绍了如何在Java中定义一个错误码枚举类`ErrCode`,用于表示各种错误情况,包括系统错误、参数错误等。接着,定义了一个`UnLoginException`异常类,继承自`RuntimeException`,并设置了特定的错误码和消息。全局异常处理类`GlobalExceptionHandler`使用`@RestControllerAdvice`注解,捕获`UnLoginException`并返回自定义的响应状态码和错误消息。这种方法在前后端分离的项目中,有助于前端根据HTTP状态码进行相应处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 定义ErrCode
**
 * 错误码 枚举
 */
public enum ErrCode {

    /**
     * 系统错误
     */
    SYSTEM_ERROR(1000, "系统错误"),

    /**
     * 参数错误
     */
    PARAMETER_ERROR(1001, "参数错误"),

    /**
     * 参数错误
     */
    NOT_NULL_ERROR(1002, "参数不能为空"),

    /**
     * 文件类型错误
     */
    FILE_TYPE_ERROR(1003, "文件类型错误"),

    /**
     * 数据不存在
     */
    DATA_IS_EMPTY(1004, "数据不存在"),

    PERMIT_FAIL(400401, "没有相关权限"),

    UNLOGIN(401, "未登录"),

    /**
     * 操作失败,一般用于修改删除,没有成功
     */
    FAIL(1004, "操作失败");


    Integer code;
    String msg;

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

    public static final Map<Integer, String> ERR_CODE = new HashMap<>();

    static {
        for (ErrCode errCode : ErrCode.values()) {
            ERR_CODE.put(errCode.getCode(), errCode.getMsg());
        }
    }

    public String getMsg() {
        return msg;
    }

    public Integer getCode() {
        return code;
    }

    public static String getMsg(Integer code) {
        String msg = ERR_CODE.get(code);
        if (!StringUtils.isEmpty(msg)) {
            return msg;
        }
        return null;
    }
}

1、定义Exception

/**
 * @author lyl
 */
@Slf4j
public class UnLoginException extends RuntimeException {
    @Getter
    private Integer code = 401;
    @Getter
    private String message;
    @Getter
    private Object data;

    public UnLoginException() {
        this(ErrCode.UNLOGIN.getCode(), ErrCode.UNLOGIN.getMsg(), null);
    }

    public UnLoginException(Object data) {
        this(ErrCode.UNLOGIN.getCode(), ErrCode.UNLOGIN.getMsg(), data);
    }


    public UnLoginException(int code, String message, Object data) {
        if (code == 0) {
            throw new RuntimeException("0 are not allowed to set !");
        }
        this.code = code;
        this.message = message;
        this.data = data;
    }
}
  1. 全局异常处理类
/**
 * @author lyl
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.UNAUTHORIZED) // 这里非常关键,这是修改的状态吗
    @ExceptionHandler(UnLoginException.class)
    public Res unloginExceptionHandler(UnLoginException e) {
        log.error("An " + e.getClass().getName() + " occurs :{}", e);
        Res res = new Res(e.getCode(), e.getMessage(), e.getData());
        return res;
    }
}
  1. 抛出异常
throw new UnLoginException()

通过以上4个步骤,就可实现抛出异常时修改http状态码,主要用在前后端分离时,前端根据状态吗进行页面跳转。

在Spring Boot中,`Filter`通常用于处理HTTP请求的预处理阶段,比如添加或修改请求头、设置响应状态码等。若你想在过滤器中返回JSON类型数据并自定义状态码,可以这样做: 1. 创建一个实现了`Filter`接口的Java类,如`MyJsonFilter`: ```java import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Component public class MyJsonFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { // 设置响应头为application/json response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 假设你想返回一个错误信息并设置状态码为400(Bad Request) String errorMessage = "Some error message"; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 构建JSON响应 Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("message", errorMessage); response.getWriter().write(new ObjectMapper()..writeValueAsString(jsonMap)); // 阻止链路继续执行,因为我们已经完成了自己的操作 chain.doFilter(request, response); } } ``` 2. 注册这个过滤器到Spring Boot应用中。你可以在`WebMvcConfigurer`接口中实现`addFilters`方法来注册它: ```java import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addFilters(FilterRegistrationBean[] filters) { Resource resource = new ClassPathResource("myJsonFilter.xml"); FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyJsonFilter()); registrationBean.setInitParameters(Collections.singletonMap("filterConfigLocation", resource.getURL().toString())); filters.add(registrationBean); } } ``` 这里假设你有一个名为`myJsonFilter.xml`的XML文件,用来配置过滤器的初始化参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值