异常分为以下三种

  • 自定义异常
  • 可预知异常
  • 不可预知异常

下面具体说明如何分类处理,从而保证无论触发什么异常均可返回理想的自定义数据格式

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处理任何异常返回通用数据格式的更多相关文章

  1. springboot2.0处理自定义异常始终返回json

    1. 编写自定义异常类 package cn.jfjb.crud.exception; /** * @author john * @date 2019/11/24 - 9:48 */ public c ...

  2. 零基础快速入门SpringBoot2.0教程 (二)

    一.SpringBoot2.x使用Dev-tool热部署 简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用 官方地址:https://docs.spring. ...

  3. SpringBoot2.0 基础案例(03):配置系统全局异常映射处理

    一.异常分类 这里的异常分类从系统处理异常的角度看,主要分类两类:业务异常和系统异常. 1.业务异常 业务异常主要是一些可预见性异常,处理业务异常,用来提示用户的操作,提高系统的可操作性. 常见的业务 ...

  4. SpringBoot2.0源码分析(四):spring-data-jpa分析

    SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(四):SpringBoot2.0之spring-data-jpa JpaRepositories自动注入 当项目中存 ...

  5. spring-boot-2.0.3之quartz集成,数据源问题,源码探究

    前言 开心一刻 着火了,他报警说:119吗,我家发生火灾了. 119问:在哪里? 他说:在我家. 119问:具体点. 他说:在我家的厨房里. 119问:我说你现在的位置. 他说:我趴在桌子底下. 11 ...

  6. SpringBoot2.0微信小程序支付多次回调问题

    SpringBoot2.0微信小程序支付多次回调问题 WxJava - 微信开发 Java SDK(开发工具包); 支持包括微信支付.开放平台.公众号.企业微信/企业号.小程序等微信功能的后端开发. ...

  7. SpringBoot2.0小程序支付功能实现weixin-java-pay

    SpringBoot2.0小程序支付功能实现weixin-java-pay WxJava - 微信开发 Java SDK(开发工具包); 支持包括微信支付.开放平台.公众号.企业微信/企业号.小程序等 ...

  8. SpringBoot2.0针对请求参数@RequestBody验证统一拦截

    title: "SpringBoot2.0针对请求参数@RequestBody验证的统一拦截"categories: SpringBoot2.0 Shirotags: Spring ...

  9. spring-boot-2.0.3应用篇 - shiro集成

    前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...

随机推荐

  1. vue中用watch监听当前路由

    之前做项目时,特别是后台项目,左边都有侧边栏,我们需要做到点击某个侧边栏的项让这个项高亮,之前采用的是给每个项绑定一个值,点击某个项时,就将这个值付给一个变量,在每一项上判断这个变量是否与每项上的值相 ...

  2. HDU 5974 A Simple Math Problem ——(数论,大连区域赛)

    给大一的排位赛中数论的一题.好吧不会做...提供一个题解吧:http://blog.csdn.net/aozil_yang/article/details/53538854. 又学了一个新的公式..如 ...

  3. 利用Apache shiro SimpleHash 加密字符串

    1.导入包 import org.apache.shiro.crypto.hash.SimpleHash; 1 2.代码 import org.apache.shiro.crypto.hash.Sim ...

  4. 2018-2019-2 20175226王鹏雲 实验四《Android程序设计》实验报告

    2018-2019-2 20175226王鹏雲 实验四<Android程序设计>实验报告 实验报告封面 课程:Java程序设计 班级:1752班 姓名:王鹏雲 学号:20175226 指导 ...

  5. Django admin site应用

    django自带的admin后台管理,可以实现对数据库表的增删改查,用起来十分方便.其使用和配置主要分为三个步骤: 1,创建超级用户 需要创建超级用户来登陆admin后台系统,在命令行中输入 pyth ...

  6. incredibuild(分布式任务软件)脚本

    IncrediBuild 可以在Server段通过修改单个任务的进程上限来实现提升任务执行速度. IncredBuild本机版也可以用来进行本机实现多线程任务分发,这样可以充分利用多核资源. 提交分布 ...

  7. C#计算两个时间年份月份天数(根据生日计算年龄)差,求时间间隔

    C#计算两个时间年份月份差 DateTime dt1 = Convert.ToDateTime("2008-8-8"); DateTime dt2 = System.DateTim ...

  8. vscode如何右键选择浏览器运行html文件

    我们利用Vscode软件编写html的时候,一般都想右键选择html文件,然后直接选择浏览器运行,但是默认是没有的: 下面鄙人给大家分享一下如何设置. 这里你会发现有好多类似的插件,你自己选择一个喜欢 ...

  9. js五彩小球

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. 小D课堂 - 新版本微服务springcloud+Docker教程_4-01 常用的服务间调用方式讲解

    笔记 第四章 服务消费者ribbon和feign实战和注册中心高可用 1.常用的服务间调用方式讲解     简介:讲解常用的服务间的调用方式 RPC:             远程过程调用,像调用本地 ...