Springboot自定义统一返回数据和自定义异常处理 异常处理

本文介绍了如何在Spring Boot中实现统一的异常处理和返回数据格式。包括创建状态码枚举类、返回数据工具类、数据拦截类、自定义异常类以及异常处理类。通过这些组件,可以标准化API的响应,提高系统的可维护性和用户体验。
摘要由CSDN通过智能技术生成

目录结构

在这里插入图片描述

创建code枚举类

package com.rj.bd.Utils;

/**
 * @author LXY
 * @desc  状态码
 * @time 2022--11--09--11:44
 */
public enum ReturnCode {
    /**操作失败**/
    RC999(999,"操作失败"),
    /**成功**/
    RC200(200,"成功"),
    /**服务降级**/
    RC201(201,"服务开启降级保护,请稍后再试!"),
    /**热点参数限流**/
    RC202(202,"热点参数限流,请稍后再试!"),
    /**系统规则不满足**/
    RC203(203,"系统规则不满足要求,请稍后再试!"),
    /**授权规则不通过**/
    RC204(204,"授权规则不通过,请稍后再试!"),
    /**access_denied**/
    RC403(403,"无访问权限,请联系管理员授予权限"),
    /**access_denied**/
    RC401(401,"匿名用户访问无权限资源时的异常"),
    /**服务异常**/
    RC500(500,"系统异常,请稍后重试"),
    INVALID_TOKEN(2001,"访问令牌不合法"),
    ACCESS_DENIED(2003,"没有权限访问该资源"),
    CLIENT_AUTHENTICATION_FAILED(1001,"客户端认证失败"),
    USERNAME_OR_PASSWORD_ERROR(1002,"用户名或密码错误"),
    UNSUPPORTED_GRANT_TYPE(1003, "不支持的认证模式");

    /**自定义状态码**/
    private final int code;
    /**自定义描述**/
    private final String message;

    ReturnCode(int code, String message){
        this.code = code;
        this.message = message;
    }
    public int getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
}

创建返回数据工具类

package com.rj.bd.Utils;

import lombok.Data;

/**
 * @author LXY
 * @desc  返回数据工具类
 * @time 2022--11--09--10:51
 */
@Data
public class ResultUtils<T> {

        private int code;
        private String message;
        private T data;


    //成功返回数据
    public static <T> ResultUtils<T> success(T data) {
        ResultUtils<T> resultUtils=new ResultUtils<T>();
        resultUtils.setCode(ReturnCode.RC200.getCode());
        resultUtils.setMessage(ReturnCode.RC200.getMessage());
        resultUtils.setData(data);
        return resultUtils;
    }

    //失败分会数据
    public static <T> ResultUtils<T> find(int code ,String mess) {
        ResultUtils<T> resultUtils=new ResultUtils<T>();
        resultUtils.setCode(code);
        resultUtils.setMessage(mess);
        return resultUtils;
    }



}

创建数据拦截类

package com.rj.bd.Config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rj.bd.Utils.ResultUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author LXY
 * @desc
 * @time 2022--11--09--11:36
 */
@RestControllerAdvice
public class CodeReture implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(o instanceof String){
            return objectMapper.writeValueAsString(ResultUtils.success(o));
        }
        if(o instanceof ResultUtils){
            return o;
        }

        return ResultUtils.success(o);
    }

}

统一返回效果展示

在这里插入图片描述

自定义异常类

package com.rj.bd.Utils;

import lombok.Getter;

/**
 * @author LXY
 * @desc  自定义异常处理
 * @time 2022-08-19  17:00
 */
@Getter
public class MyException extends RuntimeException {
    private int code;
    private String message;

    public MyException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public MyException(ReturnCode returnCode) {
        this.code = returnCode.getCode();
        this.message = returnCode.getMessage();
    }
}

自定义异常处理类

package com.rj.bd.Utils;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author LXY
 * @desc   统一异常处理
 * @time 2022--11--09--13:35
 */
@ControllerAdvice
public class excelction {

    @ResponseBody
    @ExceptionHandler(MyException.class)
    public ResultUtils handleCustomException(MyException e) {
        return ResultUtils.find(e.getCode(),e.getMessage());
    }
}

  • 异常处理效果展示
    在这里插入图片描述

如何抛异常

  try{
                computeRoom.setCoordinateType(getListUtlis.getlist(computeRoom.getGlocation()));
                computeRoom.setGlocation(null);
            }catch (Exception e){
                throw  new MyException(ReturnCode.RC500);
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值