Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json
2017-10-12 20:54
1261 查看
需求
在构建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());
}
}
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>
在构建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
- SpringBoot学习之全局异常处理设置(返回JSON)
- SpringBoot学习——全局异常处理设置(返回JSON)
- SpringBoot 统一异常处理--- @ControllerAdvice 使用
- Spring MVC 全局异常处理-RESTAPI接口返回统一JSON格式-自定义异常处理--404异常捕捉
- 异常解决篇:Spring Boot默认错误返回格式变成数组@RequestBody无法解析Json格式
- Spring boot项目设定返回数据为JSON固定格式
- Spring Boot | Cloud 的全局异常——@ControllerAdvice注解不起作用
- springboot集中处理controller层的异常(有关@ControllerAdvice的用法)
- SpringBoot RestController 同时支持返回xml和json格式数据
- spring-boot统一处理返回给前台的数据格式(避免返回异常堆栈信息,干扰用户体验)
- spring boot 全局统一格式返回自定义异常信息
- Spring-Boot--日志操作【全局异常捕获消息处理☞日志控制台输出+日志文件记录】
- Spring MVC Controller中返回json数据中文乱码处理
- 【Java】SpringBoot 引入fastjson库进行json格式数据返回实例
- SpringBoot入门——局部与全局的异常处理
- spring+mybatis返回json日期处理(日期全局处理相差8个小时解决方法)
- SpringBoot系列之三全局异常的捕获处理
- Spring Boot 快速入门实战(三)全局异常处理
- spring boot - cloud (二) 规范响应格式以及统一异常处理