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,不过原理都是相通的. 接着上一篇,这一篇 ...
随机推荐
- break语句与continue语句
break:终止该层循环: continue:跳过该层循环 注: ①:若这两个语句离开应用范围,存在是没有意义的. ②:这个两个语句后面都不能有语句,因为执行不到. ③:continue语句是跳过本次 ...
- Go http包执行流程
Go 语言实现的 Web 服务工作方式与其他形式下的 Web 工作方式并没有什么不同,具体流程如下: -- http包执行流程 Request:来自用户的请求信息,包括 post.get.Cookie ...
- Linux设备驱动程序 之 并发及其管理
竞态产生 Linux系统找那个存在大量的并发联系,因此会导致可能的竞态: 1. 正在运行的用户空间进程可以以多种组合方式访问我们的代码: 2. SMP系统甚至可以再不同的处理器上同时执行我们的代码: ...
- CPU分支预测器
两篇结合就ok啦 1.https://www.jianshu.com/p/be389eeba589 2.https://blog.csdn.net/edonlii/article/details/87 ...
- Docker Image
Docker 对 container 的使用基本是建立在 LXC 基础之上,然而 LXC 存在的问题是难以移动,难以通过标准化的模板去制作.重建.复制和移动 container. 在以 VM 为基础的 ...
- Table 'xxx.hibernate_sequence' doesn't exist
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'xxx.hibernate_sequence' ...
- PHP-生产随机密码
public function dd(){ error_reporting(E_ALL^E_NOTICE^E_WARNING);$arr1 = array(0,1,2,3,4,5,6,7,8,9);$ ...
- JAVA类定义的修饰
命名类的访问权限public.protected.friendly,private 这四个的权限, 作用域: 当前(父,超)类: 同一Package: 派生(子)类: 其他Package: publi ...
- vue active样式显示
html:代码 <ul> <li @click="current='xxxx'" :class="{active:current=='xxxx'}&qu ...
- linux下的缓存机制buffer、cache、swap
一.缓存机制介绍 在Linux系统中,为了提高文件系统性能,内核利用一部分物理内存分配出缓冲区,用于缓存系统操作和数据文件,当内核收到读写的请求时,内核先去缓存区找是否有请求的数据,有就直接返回,如果 ...