异常分为以下三种

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

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

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. 转:JSON Assertion 适用于json格式的响应断言

    当响应结果是json格式时,用JSON Assertion更方便判断. 1 在请求上右键添加json断言 2  编辑json Assertion 判断方式: 如果响应结果不是json格式的,fail ...

  2. python 鼠标输入

    import win32con import win32api import time win32api.SetCursorPos([,]) # 设置鼠标位置 time.sleep(0.1) #win ...

  3. Pytest学习笔记(一) 环境安装及入门

    简介 pytest是python的一个单元测试框架,类似于unittest,相对unittest来说,pytest使用更简单,功能更强大. 安装 pip3 install -U pytest 查看版本 ...

  4. [Shell] 分隔字符串为数组

    #!/bin/bash tmp="test,girl,boy,love" OLD_IFS="$IFS" IFS="," arr=($a) I ...

  5. Leetcode题目279.完全平方数(动态规划-中等)

    题目描述: 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n.你需要让组成和的完全平方数的个数最少. 示例 1: 输入: n = 12 输出: 3 解 ...

  6. Leetcode题目160.相交链表(简单)

    题目描述 编写一个程序,找到两个单链表相交的起始节点. 如下面的两个链表: 在节点 c1 开始相交. 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = ...

  7. redis的主从复制原理

    1. 前言 和MySQL主从复制的原因一样,Redis虽然读取写入的速度都特别快,但是也会产生读压力特别大的情况.为了分担读压力,Redis支持主从复制,Redis主从复制可以根据是否是全量分为全量同 ...

  8. 解决Powershell中不能运行脚本问题

    问题: powershell中不能执行脚本,提示‘because running scripts is disabled on this system’ 原因: powershell中默认的execu ...

  9. LeetCode 200. 岛屿的个数(Number of Islands)

    题目描述 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量.一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的.你可以假设网格的四个边均被水包围. 示例 1 ...

  10. tornado框架学习

    tornado是一个非阻塞的web服务器框架,每秒可以处理上千个客户端连接(都是在一个线程中,不需要为每个客户端创建线程,资源消耗少),适合用来开发web长连接应用,如long polling(轮询) ...