SpringMvc 全局异常处理器定义,友好的返回后端错误信息
package cn.com.servyou.gxdqy.exceptions; import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
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;
import java.util.Map; /**
* @author : hao
* @project : daieweb
* @description :
* @time : 2018/5/30 18:25
*/
@ControllerAdvice
public class WebExceptionHandler { private static Logger logger = Logger.getLogger(WebExceptionHandler.class); private static Map<String, String> messageMap = Maps.newHashMap(); static { messageMap.put("runtimeException", "运行时异常");
messageMap.put("nullPointerException", "空指针异常");
messageMap.put("classCastException", "类型转换异常");
messageMap.put("iOException", "IO异常");
messageMap.put("noSuchMethodException", "未知方法异常");
messageMap.put("indexOutOfBoundsException", "数组越界异常");
messageMap.put("httpMessageNotReadableException", "参数格式错误或没有无参构造器");
messageMap.put("typeMismatchException", "参数类型异常");
messageMap.put("missingServletRequestParameterException", "缺少参数异常");
messageMap.put("httpRequestMethodNotSupportedException", "请求类型异常");
messageMap.put("httpMediaTypeNotAcceptableException", "请求后缀异常或MediaType前后不匹配");
messageMap.put("conversionNotSupportedException", "类型注入可能非接口异常");
messageMap.put("httpMessageNotWritableException", "结果转换异常可能存在bean属性为空");
} @ExceptionHandler(RuntimeException.class)
@ResponseBody
public ResponseResult<Object> runtimeExceptionHandler(RuntimeException runtimeException) {
logger.error(runtimeException.getMessage(), runtimeException);
return RestResultGenerator.genResult(messageMap.get("runtimeException") + ":" + runtimeException.getMessage());
} @ExceptionHandler(NullPointerException.class)
@ResponseBody
public ResponseResult<Object> nullPointerExceptionHandler(NullPointerException nullPointerException) {
logger.error(nullPointerException.getMessage(), nullPointerException);
return RestResultGenerator.genResult(messageMap.get("nullPointerException") + ":" + nullPointerException.getMessage());
} @ExceptionHandler(ClassCastException.class)
@ResponseBody
public ResponseResult<Object> classCastExceptionHandler(ClassCastException classCastException) {
logger.error(classCastException.getMessage(), classCastException);
return RestResultGenerator.genResult(messageMap.get("classCastException") + ":" + classCastException.getMessage());
} @ExceptionHandler(IOException.class)
@ResponseBody
public ResponseResult<Object> iOExceptionHandler(IOException iOException) {
logger.error(iOException.getMessage(), iOException);
return RestResultGenerator.genResult(messageMap.get("iOException") + ":" + iOException.getMessage());
} @ExceptionHandler(NoSuchMethodException.class)
@ResponseBody
public ResponseResult<Object> noSuchMethodExceptionHandler(NoSuchMethodException noSuchMethodException) {
logger.error(noSuchMethodException.getMessage(), noSuchMethodException);
return RestResultGenerator.genResult(messageMap.get("noSuchMethodException") + ":" + noSuchMethodException.getMessage());
} @ExceptionHandler(IndexOutOfBoundsException.class)
@ResponseBody
public ResponseResult<Object> indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException indexOutOfBoundsException) {
logger.error(indexOutOfBoundsException.getMessage(), indexOutOfBoundsException);
return RestResultGenerator.genResult(messageMap.get("indexOutOfBoundsException") + ":" + indexOutOfBoundsException.getMessage());
} @ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public ResponseResult<Object> requestNotReadable(HttpMessageNotReadableException httpMessageNotReadableException) {
logger.error(httpMessageNotReadableException.getMessage(), httpMessageNotReadableException);
return RestResultGenerator.genResult(messageMap.get("httpMessageNotReadableException") + ":" + httpMessageNotReadableException.getMessage());
} @ExceptionHandler({TypeMismatchException.class})
@ResponseBody
public ResponseResult<Object> requestTypeMismatch(TypeMismatchException typeMismatchException) {
logger.error(typeMismatchException.getMessage(), typeMismatchException);
return RestResultGenerator.genResult(messageMap.get("typeMismatchException") + ":" + typeMismatchException.getMessage());
} @ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseBody
public ResponseResult<Object> requestMissingServletRequest(MissingServletRequestParameterException missingServletRequestParameterException) {
logger.error(missingServletRequestParameterException.getMessage(), missingServletRequestParameterException);
return RestResultGenerator.genResult(messageMap.get("missingServletRequestParameterException") + ":" + missingServletRequestParameterException.getMessage());
} @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
@ResponseBody
public ResponseResult<Object> request405(HttpRequestMethodNotSupportedException httpRequestMethodNotSupportedException) {
logger.error(httpRequestMethodNotSupportedException.getMessage(), httpRequestMethodNotSupportedException);
return RestResultGenerator.genResult(messageMap.get("httpRequestMethodNotSupportedException") + ":" + httpRequestMethodNotSupportedException.getMessage());
} @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
@ResponseBody
public ResponseResult<Object> request406(HttpMediaTypeNotAcceptableException httpMediaTypeNotAcceptableException) {
logger.error(httpMediaTypeNotAcceptableException.getMessage(), httpMediaTypeNotAcceptableException);
return RestResultGenerator.genResult(messageMap.get("httpMediaTypeNotAcceptableException") + ":" + httpMediaTypeNotAcceptableException.getMessage());
} @ExceptionHandler({ConversionNotSupportedException.class})
@ResponseBody
public ResponseResult<Object> server500(ConversionNotSupportedException conversionNotSupportedException) {
logger.error(conversionNotSupportedException.getMessage(), conversionNotSupportedException);
return RestResultGenerator.genResult(messageMap.get("conversionNotSupportedException") + ":" + conversionNotSupportedException.getMessage());
} @ExceptionHandler({HttpMessageNotWritableException.class})
@ResponseBody
public ResponseResult<Object> server500(HttpMessageNotWritableException httpMessageNotWritableException) {
logger.error(httpMessageNotWritableException.getMessage(), httpMessageNotWritableException);
return RestResultGenerator.genResult(messageMap.get("conversionNotSupportedException") + ":" + httpMessageNotWritableException.getMessage());
}
}
异常结果封装:
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class RestResultGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(RestResultGenerator.class); public RestResultGenerator() {
} public static <T> ResponseResult<List<T>> genResult(PagerBean<T> data) {
ResponseResult result = new ResponseResult();
result.setSuccess(true);
result.setData(data.getData());
result.setTotal(data.getTotal());
result.setPageIndex(data.getPageIndex());
result.setPageSize(data.getPageSize());
return result;
} public static <T> ResponseResult<T> genResult(T data, String message) {
ResponseResult result = new ResponseResult();
result.setSuccess(true);
result.setData(data);
result.setMessage(message);
return result;
} public static <T> ResponseResult<T> genResult(String error) {
ResponseResult result = new ResponseResult();
if(StringUtils.isEmpty(error)) {
result.setSuccess(true);
} else {
result.setSuccess(false);
} result.setError(error);
return result;
}
}
返回结果bean:
@JsonInclude(Include.NON_EMPTY) //为空的属性不参与序列化
public class ResponseResult<T> {
private boolean success = true;
private String error;
private T data;
private String message;
private long total;
private int pageSize;
private int pageIndex; public ResponseResult() {
} public long getTotal() {
return this.total;
} public void setTotal(long total) {
this.total = total;
} public int getPageSize() {
return this.pageSize;
} public void setPageSize(int pageSize) {
this.pageSize = pageSize;
} public int getPageIndex() {
return this.pageIndex;
} public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
} public String getError() {
return this.error;
} public void setError(String error) {
this.error = error;
} public T getData() {
return this.data;
} public void setData(T data) {
this.data = data;
} public String getMessage() {
return this.message;
} public void setMessage(String message) {
this.message = message;
} public boolean isSuccess() {
return this.success;
} public void setSuccess(boolean success) {
this.success = success;
}
}
SpringMvc 全局异常处理器定义,友好的返回后端错误信息的更多相关文章
- springmvc中拦截器与springmvc全局异常处理器的问题
最近在做一个练手的小项目, 系统架构中用了springmvc的全局异常处理器, 做了系统的统一异常处理. 后来加入了springmvc的拦截器, 为了一些需求, 在拦截器中的 preHandle 方法 ...
- springmvc全局异常后返回JSON异常数据
转自:http://www.cnblogs.com/exmyth/p/5601288.html (1)自定义或者使用spring自带的各种异常处理器 例如spring基于注解的异常解析器Annotat ...
- SpringMVC实现全局异常处理器 (转)
出处: SpringMVC实现全局异常处理器 我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手 ...
- 关于SpringMVC的全局异常处理器
近几天又温习了一下SpringMVC的运行机制以及原理 我理解的springmvc,是设计模式MVC中C层,也就是Controller(控制)层,常用的注解有@Controller.@RequestM ...
- 基于SpringMVC的全局异常处理器介绍(转)
近几天又温习了一下SpringMVC的运行机制以及原理 我理解的springmvc,是设计模式MVC中C层,也就是Controller(控制)层,常用的注解有@Controller.@RequestM ...
- 从源码看全局异常处理器@ExceptionHandler&@ExceptionHandler的生效原理
1.开头在前 日常开发中,几乎我们的项目都会用到异常处理器,我们通常会定制属于自己的异常处理器,来处理项目中大大小小.各种各样的异常.配置异常处理器目前最常用的方式应该是使用@ControllerAd ...
- 【spring】-- springboot配置全局异常处理器
一.为什么要使用全局异常处理器? 什么是全局异常处理器? 就是把错误异常统一处理的方法. 应用场景: 1.当你使用jsr303参数校验器,如果参数校验不通过会抛异常,而且无法使用try-catch语句 ...
- Spring Boot 中全局异常处理器
Spring Boot 中全局异常处理器,就是把错误异常统一处理的方法.等价于Springmvc中的异常处理器. 步骤一:基于前面的springBoot入门小demo修改 步骤二:修改HelloCon ...
- SSM之全局异常处理器
1. 异常处理思路 首先来看一下在springmvc中,异常处理的思路: 如上图所示,系统的dao.service.controller出现异常都通过throws Exception向上抛出,最后 ...
随机推荐
- 《DSP using MATLAB》示例 Example 9.11
代码: %% ------------------------------------------------------------------------ %% Output Info about ...
- 【liunx】nslookup命令
“nslookup”域名解析是什么? 假设我们要开个网站,首先我们要去提供域名申请的机构申请域名,然后绑定一个IP地址, 域名比较容易记忆,不像IP地址都是数字,申请完域名,绑定域名,DNS就写入域名 ...
- hibernate之xml映射文件关系维护,懒加载,级联
一:关系维护 --->inverse默认值false,表示不放弃关系的维护. --->inverse="true"配置在那一端,表示那一端xml对应的po放弃关系的 ...
- streamsets origin 说明
origin 是streamsets pipeline的soure 入口,只能应用一个origin 在pipeline中, 对于运行在不同执行模式的pipeline 可以应用不同的origin 独立模 ...
- gpio_get_value的定义 (转)
gpio_get_value等一系列函数,并非Linux标准函数,而是跟硬件相关的. 通常我们说的driver都是跟外围设备相关的,所以需要我们自己开发,但是这次我们说到的gpio是跟soc相关的,其 ...
- 锐捷 rg-S2026f 学习笔记
1.通过串口连接交换机: http://support.ruijie.com.cn/forum.php?mod=viewthread&tid=32250&extra=page%3D1& ...
- Python——内置函数(待完善)
内置函数(68个),分为六大类 思维导图: 1. 迭代器/生成器相关(3个) (1)range for i in range(10): #0-9 print(i) for i in range(1,1 ...
- 黄聪:VS2010启动程序提示文件加载 使用 简体中文(GB2312)编码加载文件解决办法
vs2010 错误提示框:文件加载 使用 简体中文(GB2312)编码加载文件C:\Users\Administrator\AppData\Local\Temp\nxhgjasi.5au \Temp\ ...
- GIT的安装及上传代码到码云
前言 昨天初次接触GIT及码云,虽然用了2个多小时才搞定,但是还是挺开心的.码云是一个可以储存我们写的代码的一个平台,而Git是一款免费.开源的分布式版本控制系统,可以敏捷高效地处理任何或小或大的项目 ...
- jquery.raty.js 评星插件的使用
需要实现一个五星好评的功能,所以找到了这个JQ插件,使用起来还算简单,在这里记录下使用的方式. 第一步:导入这个插件和压缩包中的img文件夹 <script type="text/ja ...