SpringBoot 通用Error设计
在项目中需要设计统一的错误消息,通常使用枚举类定义“错误码”与“错误消息”;
并且也可以做错误消息自定义。
定义通过错误接口类:CommonError
public interface CommonError {
// 获取错误码
int getErrorCode();
// 获取错误消息
String getErrorMsg();
// 设置错误消息,用于覆盖Enumeration中设置的默认错误消息
CommonError setErrorMsg(String errorMsg);
}
定义错误枚举类:EnumError
/**
* 继承至CommonError
*/
public enum EnumError implements CommonError {
// 10000开头为通用错误类型
UNKNOWN_ERROR(10001, "未知错误"),
PARAMETER_VALIDATION_ERROR(10002, "参数不合法"),
// 20000开头为用户信息相关错误码定义
USER_NOT_EXIST(20001, "用户不存在"),
USER_LOGIN_FAIL(20002, "用户名或密码错误"),
USER_NOT_LOGIN(20003, "用户未登录"),
// 定义错误码和错误消息字段
private int errorCode;
private String errorMsg;
EnumError(int errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
@Override
public int getErrorCode() {
return errorCode;
}
@Override
public String getErrorMsg() {
return errorMsg;
}
// 主要的作用:可以修改错误码对应的errorMessage
@Override
public CommonError setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
return this;
}
}
定义业务异常类:BusinessException
/**
* 包装器业务异常类实现模式
*/
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
// 通用构造器
public BusinessException(CommonError commonError){
super();
this.commonError = commonError;
}
// 覆盖ErrorMessage的构造器
public BusinessException(CommonError commonError, String errorMsg){
super();
this.commonError = commonError;
this.commonError.setErrorMsg(errorMsg);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrorMsg() {
return this.commonError.getErrorMsg();
}
// 覆盖默认的errorMessage
@Override
public CommonError setErrorMsg(String errorMsg) {
this.commonError.setErrorMsg(errorMsg);
return this;
}
}
在Controller中使用BusinessException:定义BaseController类
public class BaseController {
// 定义ExceptionHandler解决未被Controller层吸收的exception
@ExceptionHandler(value = Exception.class)
@ResponseBody
public CommonReturnType exceptionHandler(Exception ex){
Map<String, Object> responseData = new HashMap<>();
if(ex instanceof BusinessException){
BusinessException businessException = (BusinessException)ex;
responseData.put("errorCode", businessException.getErrorCode());
responseData.put("errorMsg", businessException.getErrorMsg());
} else {
responseData.put("errorCode", EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
responseData.put("errorMsg", EnumBusinessError.UNKNOWN_ERROR.getErrorMsg());
}
return CommonReturnType.create(responseData, "failed");
}
}
在UserController中实现业务逻辑
// 用户登录接口
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded")
@ResponseBody
public CommonReturnType login(@RequestParam(name = "username") String username,
@RequestParam(name = "password") String password) throws BusinessException {
// 第一步,入参校验
if(StringUtils.isEmpty(username) || StringUtils.isEmpty(username)){
throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "用户名和密码不能为空");
}
// 第二步,校验用户登录是否合法
UserModel userModel = userService.validateLogin(username, PasswordEncrypt.encodeByMd5(password));
// 第三步,加入到用户登录后的Session中
this.httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
this.httpServletRequest.getSession().setAttribute("LOGIN_USER", userModel);
return CommonReturnType.create(null);
}
SpringBoot 通用Error设计的更多相关文章
- Cocos Creator 通用框架设计 —— 资源管理优化
接着<Cocos Creator 通用框架设计 -- 资源管理>聊聊资源管理框架后续的一些优化: 通过论坛和github的issue,收到了很多优化或bug的反馈,基本上抽空全部处理了,大 ...
- 多租户通用权限设计(基于casbin)
多租户通用权限设计(基于 casbin) 所谓权限控制, 概念并不复杂, 就是确认某个操作是否能做, 本质上仅仅就是个bool判断. 权限几乎是每个系统必不可少的功能, 和具体业务结合之后, 在系统中 ...
- Android通用框架设计与完整电商APP开发系列文章
作者|傅猿猿 责编|Javen205 有福利 有福利 有福利 鸣谢 感谢@傅猿猿 邀请写此系列文章 Android通用框架设计与完整电商APP开发 课程介绍 [导学视频] [课程详细介绍] 以下是部分 ...
- SpringBoot 通用返回类设计
在项目中通常需要为前端设计通过的返回类,返回的格式为: { "status": "success", "data": {...} } 定义通 ...
- Cocos Creator 通用框架设计 —— 网络
在Creator中发起一个http请求是比较简单的,但很多游戏希望能够和服务器之间保持长连接,以便服务端能够主动向客户端推送消息,而非总是由客户端发起请求,对于实时性要求较高的游戏更是如此.这里我们会 ...
- Springboot项目架构设计
导航 前言 流水线 架构的艺术 项目架构 理解阿里应用分层架构 superblog项目架构 结语 参考 本节是<Spring Boot 实战纪实>的第7篇,感谢您的阅读,预计阅读时长3mi ...
- ASP.NET Aries 3.0发布(附带通用API设计及基本教程介绍)
主要更新: 1:升级处理机制(js请求由同步变更为异步) 2:优化前端JS:包括API和配置方式. 3:增加InputDialog功能. 4:增远远程验证功能. 5:优化权限安全机制. 6:增加一次请 ...
- 通用Adapter设计,SparseArray+泛型+回调的使用
看到题目,我相信聪明的各位已经有一定想法了. 一个Adapter,最简单的优化就是使用泛型,他可以省去非常多的代码,不过在此之上,我们还可以继续优化,优化他的好基友是:ViewHolder. 在过去, ...
- SpringBoot Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
使用SpringBoot写HelloWorld,当配置好启动类后,再创建新的controller或其它类,启动项目后访问对应的映射名,页面显示: Whitelabel Error Page This ...
随机推荐
- UIActionSheet样式问题心得
下午在做一个iPad的项目,需要用到一个 UIActionSheet. 点击popView中的“sort”按钮,触发出一个ActionSheet. self.action = [[[UIActionS ...
- Ubuntu 16.04 安装google浏览器
因为安装的Linux是64位的Ubuntu 16.04系统,所以本人决定也安装64位的谷歌Chrome浏览器.在 Ubuntu 16.04 中,要想使用谷歌的 Chrome 浏览器,可以通过命令行的方 ...
- Android编译系统入门(一)
做过Android平台开发的朋友对make,mm或make clean命令应该很熟悉,但也许大家只是熟知这些命令的作用却不知道这些命令底下有些什么原理?那么今天我就带着大家推开Android编译系统的 ...
- 网络编程4 网络编程之FTP上传简单示例&socketserver介绍&验证合法性连接
今日大纲: 1.FTP上传简单示例(详细代码) 2.socketserver简单示例&源码介绍 3.验证合法性连接//[秘钥加密(urandom,sendall)(注意:中文的!不能用)] 内 ...
- Spring Data HelloWorld(三)
在 Spring Data 环境搭建(二) 的基础之上 我们改动 http://www.cnblogs.com/fzng/p/7253068.html 定义个一个接口 继承Repository类 ...
- ubuntu14.04 编译安装CPU版caffe
本文,试图中一个干净的ubuntu14.04机器上安装caffe的cpu版本. http://blog.csdn.net/sinat_35188997/article/details/735304 ...
- Milking Time---poj3616(简单dp)
题目链接:http://poj.org/problem?id=3616 题意:人从奶牛身上挤奶有m个时间段(1----n),每个时间段包含 s e f 表示从 s 到 e 的这段时间可以获得 f 单位 ...
- Log4j:log4j.properties 配置解析
Log4j 三个主要组件 Loggers(记录器):记录日志的工具,程序中就是用它来记录我们想要的日志信息. Appenders (输出源):日志输出到什么地方,可以是控制台.文件.流位置.数据库,等 ...
- Python迭代对象、迭代器、生成器
在了解Python的数据结构时,容器(container).可迭代对象(iterable).迭代器(iterator).生成器(generator).列表/集合/字典推导式(list,set,dict ...
- spawn 和 exec 的区别(转载)
众所周知,Node.js在child_process模块中提供了spawn和exec这两个方法,用来开启子进程执行指定程序.这两个方法虽然目的一样,但是既然Node.js为我们提供了两个方法,那它们之 ...