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向上抛出,最后 ...
随机推荐
- android logger的使用
1. 进入GitHub页面 https://github.com/orhanobut/logger 2. 在gradle里增加 compile 'com.orhanobut:logger:1.15' ...
- python print 控制台输出中文
在pycharm里面的控制台用print输出信息, 本意想输出中文, 但是实际上是u\xxxx. 可以用这种方式: print("%s " % cn_string)
- jquery on() bind()绑定的点击事件在js动态新添加的元素生效
方法一:$('.class').on("click",function(){……}); 相当于 $('.class').bind("click",functio ...
- C BIN加密
#include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef DWORD #define D ...
- Zookeeper客户端 CuratorFramework使用
CuratorFramework使用 跟着实例学习ZooKeeper的用法: Curator框架应用 ZooKeeper客户端Curator使用一 创建连接
- 简单对象访问协议(Simple Object Access Protocol),PHP调用SOAP过程中的种种问题;php的soap无故出错的真凶:wsdl缓存
webservice的一种常用实现方式就是soap了.我们后端的JAVA也是用soap的原理实现的.那么我显然首先要上网上搜搜关于soap的文章.最早进入实现的是PHP写的nusoap类.这个n ...
- 使用css弹性盒子模型
提示: 当期内容不充实, 修改后再来看吧 以下称:弹性子元素: 子元素, 弹性容器: 容器 弹性盒子的属性 1. css弹性盒子模型规定了弹性元素如何在弹性容器内展示 2. 弹性元素默认显示在弹性容器 ...
- python入门第3篇 pycharm安装及使用
内容: 1. python开发工具的介绍及安装 2.pycharm的设置及技巧 一.python开发工具的介绍及安装 python下载后就自带了一个官方的IDE,官方的IDE我个人觉得不是很好用,所以 ...
- FTP和TCP、UDP
应用:TFTP客户端 1. TFTP协议介绍 TFTP(Trivial File Transfer Protocol,简单文件传输协议) 是TCP/IP协议族中的一个用来在客户端与服务器之间进行简单文 ...
- linux下创建具有root权限的账户
http://blog.chinaunix.net/uid-24631445-id-2981034.html