搭建springboot后端框架(六)自定义异常+后端统一响应消息

项目搭建工具及版本:

eclipse / jdk1.8 / springboot2.5.0 

实现功能:

主要实现2个点,自定义的异常捕获返回给请求方,正常请求的统一返回处理。

1.主要功能类说明

错误码枚举类、响应返回实体类、响应返回实体工具类、自定义异常、自定义异常拦截器配置类

 2.源代码

package com.bbnet.common.exception;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 常见的错误枚举类
 *
 *
 * @author sgc
 * @since 2021-08-27
 */
@Getter
@AllArgsConstructor
public enum  ErrorEnum {
	
    RESP_CODE_SUCC("0","请求成功"),
    RESP_CODE_FAIL("1","请求失败"),
    RESP_CODE_NO_TOKEN("-1","TOKEN为空"),
    RESP_CODE_TIMEOUT("-2","会话超时或非法请求");

    /**
     * 错误码
     */
    private String code;

    /**
     * 提示信息
     */
    private String msg;
}
package com.bbnet.common.exception;

import lombok.Data;

/**
 * 响应对象
 *
 * @param <T>
 *
 * @author sgc
 * @since 2021-08-27
 */
@Data
public class ResponseResult<T> {

		/**
		 * 状态码
		 */
		private String code;

		/**
		 * 提示信息
		 */
		private String msg;
		
		/**
		 * 请求成功时返回的对象
		 */
		private T data;

}
package com.bbnet.common.exception;

/**
 * 响应对象工具类
 *
 *
 * @author sgc
 * @since 2021-08-27
 */
public class ResponseUtils {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ResponseResult success(Object obj){
		ResponseResult res = new ResponseResult();
		res.setCode(ErrorEnum.RESP_CODE_SUCC.getCode());
		res.setData(obj);
		res.setMsg(ErrorEnum.RESP_CODE_SUCC.getMsg());
		return res;
	}

	@SuppressWarnings("rawtypes")
	public static ResponseResult success(){
		return success(null);
	}

	@SuppressWarnings("rawtypes")
	public static ResponseResult error(String code, String msg){
		ResponseResult res = new ResponseResult();
		res.setCode(code);
		res.setMsg(msg);
		return res;
	}

}

package com.bbnet.common.exception;

import lombok.Getter;

/**
 * 自定义异常
 *
 *
 * @author sgc
 * @since 2021-08-27
 */
@Getter
public class ServiceException extends RuntimeException{
	
	private static final long serialVersionUID = 7133651385712198609L;
	private String code;

    /**
     * 使用已有的错误类型
     * @param type 枚举类中的错误类型
     */
    public ServiceException(ErrorEnum type){
        super(type.getMsg());
        this.code = type.getCode();
    }

    /**
     * 自定义错误类型
     * @param code 自定义的错误码
     * @param msg 自定义的错误提示
     */
    public ServiceException(String code, String msg){
        super(msg);
        this.code = code;
    }
}
package com.bbnet.common.exception;

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

import com.bbnet.common.encrypt.annotation.Encrypt;

/**
 * 异常处理类
 *
 *
 * @author sgc
 * @since 2021-08-27
 */
@ControllerAdvice 
public class ServiceExceptionHandler {

    /**
     * <pre>
     * ExceptionHandler相当于controller的@RequestMapping
     * 如果抛出的的是ServiceException,则调用该方法
     * </pre>
     * 
     * @param se 业务异常
     * @return
     */
    @SuppressWarnings("rawtypes")
	@ExceptionHandler(ServiceException.class)
    @ResponseBody
    @Encrypt
    public ResponseResult handle(ServiceException se){
        return ResponseUtils.error(se.getCode(), se.getMessage());
    }
}

3.测试

如下面的部分代码,如有异常可以直接抛出,如正常返回直接返回ResponseUtils.success()或者ResponseUtils.success(Obj)

//code...

    @SuppressWarnings("rawtypes")
	@ApiOperation(value="删除token接口", notes="token时效情况下删除token,即类似于退出登录")
    @PostMapping("/removeToken")
    public ResponseResult removeToken(@RequestBody Token token) {
		//参数校验
		if(oConvertUtils.isEmpty(token.getAccount())) {
			throw new ServiceException(ErrorEnum.RESP_CODE_FAIL.getCode(), "账号或用户名为空");
		}
		
		//account的加密结果
		String accountEnc = AES.aesEncryptBase64(token.getAccount());
		//bbnet:user_prefix_token:002604_MnJMUnY1TWNhVmZsMXlLQjNkajR6QT09
		String key = ServiceConstants.TOKEN_PREFIX+token.getAccount()+"_"+accountEnc;
		log.info("Token的key为:{}", key);
		
		//如果已经存在token直接返回
		if(redisService.hasKey(key)) {
			redisService.del(key);
		}
		
		return ResponseUtils.success();
	}


//code...
package com.bbnet.common.base.token;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
@ApiModel(value="TOKEN报文实体")
public class Token {
	
	@ApiModelProperty(value = "账号/用户名", dataType = "String")
	String account;
	
	@ApiModelProperty(value = "口令/密码", dataType = "String")
	String password;

}

比如以下请求示例截图:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一个由Pivotal团队提供的全新框架,旨在简化新Spring应用程序的初始化搭建和开发过程。它采用特定的配置方式,使开发人员无需编写样板化的配置。Spring Boot的优点包括: 1. 简化配置:Spring Boot提供了自动配置的功能,大大减少了配置文件的编写工作,使开发更加便捷。 2. 快速开发:Spring Boot提供了一套可靠的开发环境和开发工具,可以快速构建后端应用程序。 3. 自动化依赖管理:Spring Boot的依赖管理功能可以自动管理项目的依赖关系,简化了项目的依赖管理过程。 4. 内嵌服务器:Spring Boot内置了Tomcat等常用服务器,使得部署和运行应用程序变得更加简单。 5. 易于测试:Spring Boot提供了方便的测试工具和注解,可以轻松地进行单元测试和集成测试。 总之,Spring Boot是一个强大而灵活的后端框架,它通过简化配置、提供便利的开发工具和自动化依赖管理等特性,使得开发人员能够更加轻松地构建高效、可靠的后端应用程序。 [2 [3<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [后端框架SpringBoot入门](https://blog.csdn.net/qq_40401866/article/details/102480841)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【开发】后端框架——SpringBoot](https://blog.csdn.net/qq_40479037/article/details/129786063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cgv3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值