springboot2.0处理任何异常返回通用数据格式
异常分为以下三种
- 自定义异常
- 可预知异常
- 不可预知异常
下面具体说明如何分类处理,从而保证无论触发什么异常均可返回理想的自定义数据格式
ResultCode
/**
* Created by mrt on 2018/3/5.
* 10000-- 通用错误代码
* 22000-- 媒资错误代码
* 23000-- 用户中心错误代码
* 24000-- cms错误代码
* 25000-- 文件系统
*/
public interface ResultCode {
//操作是否成功,true为成功,false操作失败
boolean success();
//操作代码
int code();
//提示信息
String message();
}
ResponseResult
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
public class ResponseResult implements Response {
//操作是否成功
boolean success = SUCCESS;
//操作代码
int code = SUCCESS_CODE;
//提示信息
String message;
public ResponseResult(ResultCode resultCode) {
this.success = resultCode.success();
this.code = resultCode.code();
this.message = resultCode.message();
}
public static ResponseResult SUCCESS() {
return new ResponseResult(CommonCode.SUCCESS);
}
public static ResponseResult FAIL() {
return new ResponseResult(CommonCode.FAIL);
}
}
自定义异常类
import com.xuecheng.framework.model.response.ResultCode;
/**
* 自定义异常
*
* @author john
* @date 2019/12/20 - 10:57
*/
public class CustomException extends RuntimeException {
private ResultCode resultCode;
public CustomException(ResultCode resultCode) {
//异常信息为错误代码+异常信息
super("错误代码:" + resultCode.code() + "错误信息:" + resultCode.message());
this.resultCode = resultCode;
}
public ResultCode getResultCode() {
return this.resultCode;
}
}
CommonCode (自定义异常信息返回数据枚举类)
import lombok.ToString;
@ToString
public enum CommonCode implements ResultCode{
INVALID_METHOD(false,10004,"非法方法!"),
INVALID_PARAM(false,10003,"非法参数!"),
SUCCESS(true,10000,"操作成功!"),
FAIL(false,11111,"操作失败!"),
UNAUTHENTICATED(false,10001,"此操作需要登陆系统!"),
UNAUTHORISE(false,10002,"权限不足,无权操作!"),
SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!");
// private static ImmutableMap<Integer, CommonCode> codes ;
//操作是否成功
boolean success;
//操作代码
int code;
//提示信息
String message;
private CommonCode(boolean success,int code, String message){
this.success = success;
this.code = code;
this.message = message;
}
@Override
public boolean success() {
return success;
}
@Override
public int code() {
return code;
}
@Override
public String message() {
return message;
}
}
异常处理(包含自定义异常和不可预见异常和可预见异常)
import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author john
* @date 2019/12/20 - 11:01
*/
@Slf4j
@ControllerAdvice
public class ExceptionCatch {
//使用EXCEPTIONS存放异常类型和错误代码的映射,ImmutableMap的特点的一旦创建不可改变,并且线程安全
private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
//使用builder来构建一个异常类型和错误代码的异常
protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder =
ImmutableMap.builder();
static {
//在这里加入一些基础的异常类型判断---异常存在非自定义异常
// 参数异常
// 请求方法异常
builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
builder.put(HttpRequestMethodNotSupportedException.class, CommonCode.INVALID_METHOD);
}
//捕获 CustomException异常
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException e) {
log.error("catch exception : {}\r\nexception: ", e.getMessage(), e);
ResultCode resultCode = e.getResultCode();
return new ResponseResult(resultCode);
}
//捕获Exception异常---非自定义异常
@ResponseBody
@ExceptionHandler(Exception.class)
public ResponseResult exception(Exception e) {
log.error("catch exception : {}\r\nexception: ", e.getMessage(), e);
if (EXCEPTIONS == null)
EXCEPTIONS = builder.build();
// 查看异常是否被定义返回格式---没有就返回默认错误格式
final ResultCode resultCode = EXCEPTIONS.get(e.getClass());
final ResponseResult responseResult;
if (resultCode != null) {
responseResult = new ResponseResult(resultCode);
} else {
responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
}
return responseResult;
}
}

springboot2.0处理任何异常返回通用数据格式的更多相关文章
- springboot2.0处理自定义异常始终返回json
1. 编写自定义异常类 package cn.jfjb.crud.exception; /** * @author john * @date 2019/11/24 - 9:48 */ public c ...
- 零基础快速入门SpringBoot2.0教程 (二)
一.SpringBoot2.x使用Dev-tool热部署 简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用 官方地址:https://docs.spring. ...
- SpringBoot2.0 基础案例(03):配置系统全局异常映射处理
一.异常分类 这里的异常分类从系统处理异常的角度看,主要分类两类:业务异常和系统异常. 1.业务异常 业务异常主要是一些可预见性异常,处理业务异常,用来提示用户的操作,提高系统的可操作性. 常见的业务 ...
- SpringBoot2.0源码分析(四):spring-data-jpa分析
SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(四):SpringBoot2.0之spring-data-jpa JpaRepositories自动注入 当项目中存 ...
- spring-boot-2.0.3之quartz集成,数据源问题,源码探究
前言 开心一刻 着火了,他报警说:119吗,我家发生火灾了. 119问:在哪里? 他说:在我家. 119问:具体点. 他说:在我家的厨房里. 119问:我说你现在的位置. 他说:我趴在桌子底下. 11 ...
- SpringBoot2.0微信小程序支付多次回调问题
SpringBoot2.0微信小程序支付多次回调问题 WxJava - 微信开发 Java SDK(开发工具包); 支持包括微信支付.开放平台.公众号.企业微信/企业号.小程序等微信功能的后端开发. ...
- SpringBoot2.0小程序支付功能实现weixin-java-pay
SpringBoot2.0小程序支付功能实现weixin-java-pay WxJava - 微信开发 Java SDK(开发工具包); 支持包括微信支付.开放平台.公众号.企业微信/企业号.小程序等 ...
- SpringBoot2.0针对请求参数@RequestBody验证统一拦截
title: "SpringBoot2.0针对请求参数@RequestBody验证的统一拦截"categories: SpringBoot2.0 Shirotags: Spring ...
- spring-boot-2.0.3应用篇 - shiro集成
前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...
随机推荐
- Python基础之for循环
for循环:用户按照顺序循环可迭代对象的内容 1. for循环字符串 msg = "string" for i in msg: print(i) 执行结果为: s t r i n ...
- Linux 上的Tomcat配置输入域名直接访问项目
申请的域名备案通过了,域名是在阿里云上面的买的,一块钱,当初买服务器是买着来玩玩的. 既然申请的域名已经备案通过了,也配置了域名解析 ,服务器上也装了Tomcat,部署了web项目,下面来配置下通过域 ...
- mac使用jadx逆向app
安装jadx 编译安装 git clone https://github.com/skylot/jadx.git cd jadx ./gradlew dist 然后将build/jadx/bin加入到 ...
- 单调队列优化dp(捡垃圾的机器人)
/************************************************************************* > File Name: a.cpp > ...
- LeetCode 41. 缺失的第一个正数(First Missing Positive)
题目描述 给定一个未排序的整数数组,找出其中没有出现的最小的正整数. 示例 1: 输入: [1,2,0] 输出: 3 示例 2: 输入: [3,4,-1,1] 输出: 2 示例 3: 输入: [7,8 ...
- Android-Glide使用
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Li_Qing_Xue/article/details/78919499 图片加载很是重要,我也对比过 ...
- UIGestureRecongnizer 手势拦截 对于特殊需求很有用
手势其实也有代理方法的,通过代理方法可以做到更多关于手势方面的功能 比如在下面的方法中,如果是UIButton的点击就阻止手势的点击事件. // called before touchesBegan: ...
- EBR-TLV数据格式
EMV规范中的BER-TLV数据格式:BER-TLV结构由Tag.Length.Value三部分组成. [TAG域]TAG可以由1个与多个字节组成,TAG域的第一个字节编码格式如下: 其中由三部分组成 ...
- 用JSON文本动态创建DataGrid
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...
- flutter richText富文本
flutter中富文本使用 RichText( text: TextSpan( text: '登陆即同意', style: TextStyle(fontSize: 14, color: Colors. ...