Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json
- 需求
在构建RestFul的今天,我们一般会限定好返回数据的格式比如:
{
"code": 0,
"data": {},
"msg": "操作成功"}
但有时却往往会产生一些bug。这时候就破坏了返回数据的一致性,导致调用者无法解析。所以我们常常会定义一个全局的异常拦截器。
注意:ControllerAdvice注解 只拦截Controller 不回拦截 Interceptor的异常 介绍
在spring 3.2中,新增了@ControllerAdvice 注解,用于拦截全局的Controller的异常,注意:ControllerAdvice注解只拦截Controller不会拦截Interceptor的异常代码
package com.cmc.schedule.handler;import com.gionee.base.entity.JsonResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.ConversionNotSupportedException; import org.springframework.beans.TypeMismatchException; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody;import java.io.IOException;/*** 异常拦截处理器** @author chenmc*/ @ControllerAdvice @ResponseBody public class GlobalExceptionHandler {private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);//运行时异常 @ExceptionHandler(RuntimeException.class)public String runtimeExceptionHandler(RuntimeException ex) {return resultFormat(1, ex);}//空指针异常 @ExceptionHandler(NullPointerException.class)public String nullPointerExceptionHandler(NullPointerException ex) {return resultFormat(2, ex);}//类型转换异常 @ExceptionHandler(ClassCastException.class)public String classCastExceptionHandler(ClassCastException ex) {return resultFormat(3, ex);}//IO异常 @ExceptionHandler(IOException.class)public String iOExceptionHandler(IOException ex) {return resultFormat(4, ex);}//未知方法异常 @ExceptionHandler(NoSuchMethodException.class)public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {return resultFormat(5, ex);}//数组越界异常 @ExceptionHandler(IndexOutOfBoundsException.class)public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {return resultFormat(6, ex);}//400错误 @ExceptionHandler({HttpMessageNotReadableException.class})public String requestNotReadable(HttpMessageNotReadableException ex) {System.out.println("400..requestNotReadable");return resultFormat(7, ex);}//400错误 @ExceptionHandler({TypeMismatchException.class})public String requestTypeMismatch(TypeMismatchException ex) {System.out.println("400..TypeMismatchException");return resultFormat(8, ex);}//400错误 @ExceptionHandler({MissingServletRequestParameterException.class})public String requestMissingServletRequest(MissingServletRequestParameterException ex) {System.out.println("400..MissingServletRequest");return resultFormat(9, ex);}//405错误 @ExceptionHandler({HttpRequestMethodNotSupportedException.class})public String request405(HttpRequestMethodNotSupportedException ex) {return resultFormat(10, ex);}//406错误 @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})public String request406(HttpMediaTypeNotAcceptableException ex) {System.out.println("406...");return resultFormat(11, ex);}//500错误 @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})public String server500(RuntimeException ex) {System.out.println("500...");return resultFormat(12, ex);}//栈溢出@ExceptionHandler({StackOverflowError.class})public String requestStackOverflow(StackOverflowError ex) {return resultFormat(13, ex);}//其他错误@ExceptionHandler({Exception.class})public String exception(Exception ex) {return resultFormat(14, ex);}private <T extends Throwable> String resultFormat(Integer code, T ex) {ex.printStackTrace();log.error(String.format(logExceptionFormat, code, ex.getMessage()));return JsonResult.failed(code, ex.getMessage());}}
package com.cmc.base.entity;import com.alibaba.fastjson.JSON; import lombok.Data;import java.io.Serializable; import java.util.HashMap; import java.util.Map;/*** @author chenmc* @date 2017/10/12 17:18*/ @Data public class JsonResult implements Serializable{private int code; //返回码 非0即失败private String msg; //消息提示private Map<String, Object> data; //返回的数据public JsonResult(){};public JsonResult(int code, String msg, Map<String, Object> data) {this.code = code;this.msg = msg;this.data = data;}public static String success() {return success(new HashMap<>(0));}public static String success(Map<String, Object> data) {return JSON.toJSONString(new JsonResult(0, "解析成功", data));}public static String failed() {return failed("解析失败");}public static String failed(String msg) {return failed(-1, msg);}public static String failed(int code, String msg) {return JSON.toJSONString(new JsonResult(code, msg, new HashMap<>(0)));}}
Spring Boot这样就可以了,如果是没用Spring Boot的话,需要在SpringMvc的配置文件中增加下面的配置
<!-- 处理异常 --><context:component-scan base-package="com.gionee.xo" use-default-filters="false"> <!-- base-package 如果多个,用“,”分隔 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <!--控制器增强,使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常--> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan>
Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json相关推荐
- spring boot 四:全局异常捕捉
spring boot 四:全局异常捕捉 1 前言 希望定制错误,比如一般springboot的500错误展示如下(trace等可以通过配置application.yml来决定隐藏还是具有): app ...
- 无返回值_只需一步,在Spring Boot中统一Restful API返回值格式与处理异常
统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: public cl ...
- Spring Boot 统一处理全局异常
目录 注解的介绍 @ControllerAdvice @ExceptionHandler拦截异常并统一处理 代码实现 自定义异常 统一异常处理 前端返回值类 测试用例 如果本篇博客对您有一定的帮助,大 ...
- springboot怎么返回404_Spring Boot2 系列教程(十三)Spring Boot 中的全局异常处理
在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @ControllerAdvice 来统一处理,也可以自己来定义异常处理方案.Spring Boot 中,对异常的处理有 ...
- Spring Boot 工程集成全局唯一ID生成器 Vesta
2019独角兽企业重金招聘Python工程师标准>>> 本文内容脑图如下: 文章共 760字,阅读大约需要 2分钟 ! 概 述 在前一篇文章 <Spring Boot工程集成全 ...
- Spring Boot微服务间文件返回实现
Feign接口获取文件流问题_Java_wyazyf的博客-CSDN博客 https://blog.csdn.net/wyazyf/article/details/93200033 Spring Bo ...
- spring boot 搭建 和 全局异常处理
spring boot 搭建: java -jar -Dserver.port=10000 -Dlogging.path=/var/logs xxx.jar & -- 默认在/var/lo ...
- Spring Boot 无侵入式 实现 API 接口统一 JSON 格式返回
点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 无侵入式 统一返回JSON格式 其实本没有没打算写这篇博客 ...
- Spring Boot 无侵入式 实现API接口统一JSON格式返回
作者 | 小魏小魏我们去那里呀 来源 | blog.csdn.net/qq_34347620/article/details/102239179 无侵入式 统一返回JSON格式 其实本没有没打算写这篇 ...
最新文章
- 2020 年度最佳的23个机器学习项目!(附源代码)
- R语言ggplot2可视化分面图(faceting)、可视化分面条形图(facet_wrap bar plot)、使用strip.text函数自定义分面图每个分面标题条带strip的大小(cutomi
- JavaMail邮件别名和主题乱码解决[转]
- MySQL优化器:index merge介绍
- html卷轴展开,HTML文本框滚动代码4:卷轴变化应用
- SpringMVC实现RESTful风格
- 如何将一个目录下的所有文件,合并成一个文件
- GroupMetadataManager分析
- oracle dba create view 失败 解决办法
- 注意判断js中使用正则表达式的转义字符,到底是对谁进行转义!!!
- ActiveMQ 简介、安装、与 Maven 项目基本使用
- STM32F407 硬件IIC驱动MCP4017 数字电位器
- 按键精灵助手之按钮响应事件
- 收集广州周边徒步线路
- Dede文章标题及文章摘要长度修改_元曦血狼_新浪博客
- 【成本收集器】目标成本与实际成本差异分析
- 教程篇(6.4) 02. FortiOS架构 ❀ 企业防火墙 ❀ Fortinet 网络安全架构师 NSE7
- 软件开发—钱多多—典型用户分析
- python爬虫和定位_Python网络爬虫实战(三)照片定位与B站弹幕
- 软件配置项变更与基线变更